💻
IT Documentation
  • 🥳Welcome!
  • General Concepts
    • SCRUM
      • Workflow
    • DevOps
      • What is DevOps?
      • What is TDD? (Test Driven Development)
      • What is CI? (Continuous Integration)
      • What is code coverage?
      • Linting best practices
      • Ephemeral Environments
      • Rolling Deployments
      • Blue/Geen Deployments
      • Canary Deployments
      • What is autoscaling & serverless?
      • What is service discovery?
      • What is Log Aggregation?
      • Metric Monitoring
  • AI
    • ChatGPT
      • Better prompts for ChatGPT
  • Cloud
    • AWS
      • AWS - 40 most common Services
      • AWS CLI Cheatsheet
      • Account & IAM
        • Create AWS Account
      • Lambda
        • Create Lambda function for Lightsail
      • Route 53
        • Set up R53 DNS Entry for GitBook
      • RDS
        • AWS RDS Burst Balance
      • VPC
        • What is a VPC
      • EC2
        • Removing EC2 user from sudo list
        • Create a Windows Gaming VPS
        • Connecting to a AWS EC2 instance
    • Azure
      • Courses
        • AZ900 Course
          • Overview
            • Describe Core Concepts
            • Cloud Models (IaaS, PaaS, SaaS)
          • Benefits of Cloud Computing
          • Cloud Models and Cloud Types
            • Overview of Cloud Models
            • IaaS, PaaS, SaaS
            • The Serverless Model
            • Cloud Types
          • Core Azure Architectural Components
            • Overview
            • Regions & Availability Zones
            • Resource Groups & Subscriptions & Management Groups
            • Resources & Resource Manager
          • Core Resources available
            • Compute Resources
            • Networking Resources
            • Storage Resources
            • Database Services
            • Azure Marketplace
          • Azure Core Solutions
            • Overview
            • Internet of Things (IoT) Solutions
            • Big Data Solutions
            • AI Solutions
            • Azure Functions & Logic Apps and Event Grid
            • DevOps Solutions
          • Azure Management Tools
            • Overview
            • Managing Azure with ARM Templates
            • Azure Monitor & Azure Service Health
          • Azure Security Features
            • Overview
            • Azure Security Center
            • Azure Key Vault & Azure Sentinel
            • Azure Dedicated Hosts
          • Azure Network Security
            • Network Security Group (NGS), Firewall and DDoS Protection
          • Azure Identity Services
            • Overview
            • Benefits
            • Multi-Factor Authentication (MFA)
            • Authentication vs Authorization
          • Azure Governance Features
            • Authentification and RBAC
            • Resource Locks
            • Azure Policy
            • Azure Blueprints
            • Cloud Adoption Framework (CAF)
          • Compliance Features
            • Core tenets of Security, Privacy and Compliance
            • Privacy Statement and Online Service Terms (OST)
            • Trust Center
            • Azure Sovereign Regions
          • Manage Azure Costs
            • Overview
            • Best practices
            • Pricing calculator
            • Azure Cost Management
          • SLA (Service level Agreements)
      • Virtual Machines
        • VM
          • Create a VM in a VNET
          • Azure VM LVM corruption fix
        • VMSS
          • Add SSH Key to VMSS
  • Containerization
    • Docker
      • Docker Cheatsheet
      • Install docker on Debian
      • Docker misc stuff
    • Docker Swarm
      • Docker Swarm Cheatsheet
      • Set up docker swarm
      • Delete docker swarm
      • Mount and bind volumes
      • Deploy Portainer via docker swarm
    • Docker Compose
      • Jenkins via Docker Compose
      • PostgreSQL via Docker Compose
      • Wireguard via Docker Compose & HTTPS
    • Rancher
      • Rancher installation guide
  • Cluster Computing
    • Slurm
      • Job Manager is not responding
      • Create new user
    • OpsCenter
      • Clear old Snapshots
      • Issues listing snapshots with nodetool
  • Database
    • General SQL
      • Database introduction
      • SQL 101
      • SQL Cheatsheet
      • User rights
      • Table Creation
      • SQL Replication - Best practice
      • SQL Database Design
    • MS SQL
      • Update whole table fast
    • Oracle SQL (PL/SQL)
      • Oracle SQL Cheatsheet
      • Oracle SQL - Kill Sessions
    • PostgreSQL
      • Install PostgreSQL
      • Create PostgreSQL Role and Database
      • Managing Postgres with PgAdmin GUI
      • Enable remote access for PostgreSQL
      • Authentication on PostgreSQL
      • Returning in Postgres
    • SQLite
    • Flyway Overview
    • SSRS Overview
    • Cassandra
      • GC OutOfMemoryError
  • DevOps
    • Ansible
      • Ansible Cheatsheet
      • Common Ansible Tasks
    • Git
      • Git 101
      • Git 1kb files
      • Git Commit changes before merge
      • Git Misc
      • Git Markdown
      • Git Clone Repo via SSH
    • Github
      • How to use multiple accounts
      • Delete commits fully
      • Set up git ignore file
    • Github Actions
      • Install self hosted runner
      • Scheduling jobs cron style
      • Passing ENV variable in script
      • SSH to Server
    • GitLab
      • GitLab Cheatsheet
    • Terraform
      • Terraform components
  • Hardware
    • UPS - Njoy
  • IoT
    • Home Assistant
      • Valetudo configs
      • Mini Media Player
      • HACS
    • Valetudo
      • Roborock Gen 1
      • Roborock quick guide
      • Roborock full Valetudo install guide
    • Tasmota
      • Tuya-Convert
    • LibreELEC
      • Quick LibreELEC guide
      • Configure X96 Mini Remote
  • OS
    • Linux
      • Learning guidelines
        • LPIC1 Notes
        • Linux Academy Notes
      • Install / Update Guides
        • Set up Raspberry PI
        • Update Debian 10 (buster) to Debian 11 (bullseye)
      • Increase disk size
      • umask
      • inodes
      • at jobs
      • yum
        • yum update vs yum upgrade
      • find
      • ssh
        • SSH returns: no matching host key type found. Their offer: ssh-rsa
        • Generate Public Key from Private Key
        • Run local bash scripts on remote server
      • crontab
        • Crontab 1st Sunday of every Month
        • Set crontab to execute after restart
      • vim
        • Use sed inside vim
      • networking
        • Check Port
      • fail2ban
      • bashrc
      • lvm
      • fallocate
        • Generate dummy file with actual size
      • openssl
        • Create Certificate via CNF file
        • OpenSSL cert conversion
    • Windows
      • Windows - Get App port by PID
      • Windows - Upgrade Windows build
      • Windows - Server
    • Android
      • Android - Motorola Unlock
      • Android - /E Project
    • PinePhone
      • PinePhone - Instructions for creating a PureOS image for PinePhone
  • Monitoring
    • Nagios
      • CPU threshold value calculation
    • New Relic
      • New Relic Flex Integration
      • NRQL Alerts examples
    • Zabbix
      • Zabbix Proxy not communicating with Windows Server
  • Microsoft Suite
    • Outlook
      • Change View
    • Excel
      • Excel Shortcuts
    • Windows Subset for Linux
      • WSL no internet connection
  • Networking
    • General Networking
      • IP Classes and Subnet Masks
      • Network CIDR Charts - /-es or IP Prefix
      • OSI Model Overview
      • Three Way Handshake & TCP Overview
    • F5
    • Authelia
      • What is Authelia
    • Nginx Proxy Manager
      • Nginx Proxy Manager - DuckDNS going down
    • Nmap
    • OpenWRT
      • Securing OpenWRT
      • OpenWRT - Read logs
      • OpenWRT - Adding DHCP Entry
      • OpenWRT - Wireguard
      • OpenWRT - Set up OpenVPN
      • OpenWRT - Internal DNS Service
      • OpenWRT - Set up new Wifi Interface
      • OpenWRT - Set up VLAN
      • OpenWRT - VPN Policy Routing
    • Pihole
      • Enabling HTTPS for your Pihole Web Interface
      • Edit Pihole DNS entries
    • RVS
      • RVS - Observer Modification
      • RVS - All Parameters
      • RVS - Adding a station
    • Wireguard
    • FTP
      • Connect to FTP anonymously
  • Pen Testing
    • CTF
      • CTF Links
  • Programming
    • Python
      • Classic Python
        • Python Cheatsheet
        • Python Shortcuts
        • Dunder Methods
        • hasattr(), getattr(), delattr()
        • Useful Exceptions
        • Dictionary
        • isinstance()
        • isdigit(), isdecimal(), isalpha()
        • return
        • Functions
        • Lists
        • ord(), chr()
        • squares, twos, odds
        • Bubble sort
        • append() and insert()
        • Bitwise operators
        • while, for & else
        • Arithmetic Operators
        • equal operators
        • Structure Projects
      • Modules
        • Webscraping
          • BeautifulSoup
        • PySimpleGui
          • Fast Crashcourse on PySimpleGui
        • os
        • python-docx
          • Generate DOCX file
        • psycopg2
          • PostgreSQL Connection
        • Pydantic Model vs SQLAlchemy Model
      • Frameworks
        • FastAPI
          • FastAPI Quick overview
          • Installing FastAPI and Dependencies
          • Starting FastAPI
          • Path Operations
          • Creating HTTP Operation paths
          • Send Data via Body of HTTP Request
          • Schema Validation with Pydantic
          • CRUD Operations
          • Storing in Array
          • Retrieve one individual entry
          • Changing response Status Codes
          • Deleting entries
          • Updating entries
          • API Documentation
          • Setup App Database & connect to database
          • FastAPI Response Model via Pydantic
          • Hashing passwords via FastAPI
          • Getting user by ID
          • FastAPI Routers
          • Router Prefix
          • Router Tags
          • JWT Token Basics
          • Login Process
          • Creating Token with OAuth2
          • OAuth2 PasswordRequestForm
          • Verify user is Logged In
          • Protecting Routes
          • Fetching User in Protected Routes
        • SQLAlchemy
          • What is an ORM
          • SQLAlchemy setup
          • Adding CreatedAt Column
          • CRUD via SQLAlchemy
          • Efficient way of passing params in SQLAlchemy
          • Creating Users Table via SQLAlchemy & FastAPI
      • Virtual Environments (venv)
    • General Programming Concepts
    • Interview Questions & Answers
      • General Programming Questions
      • Python Interview Questions Beginner
    • Courses
      • Python - PCAP-31-03 Course
        • Overview & Introduction
          • Exam Syllabus
          • Basics of variables
          • Basic Data Types
          • Basic Arithmetic in Python
          • Indexing and Slicing Strings
          • Basic String Methods
          • Format Method
          • Strings are Immutable
        • Lists, Tuples and Dictionaries
          • Lists
          • Accessing Elements in Nested Lists
          • Finding Index positions in Lists and counting duplicates
          • Tuples
          • Dictionaries
          • Comparison Operators
        • Functions and Variable Scope
          • Creating functions
          • *args and **kwargs
          • Basic Variable scope
          • Scope and Nested functions
        • Control Flow
          • If & Else Statements
          • Elif Statements
          • For Loops
          • Pass Statement in For Loops
          • While Loops
          • Looping and Unpacking with Dictionaries and Tuples
          • Range, Enumerate and Zip Functions
          • More Handy Functions and the Random Package
          • Accepting Input from User
        • Modules, Packages and OOP
          • Revising the Difference between Methods and Functions
          • Classes and Objects
          • Classes Attributes vs Object Attributes
          • Calling Python Code that is Saved in Another File
          • Inheritance and Polymorphism
          • Abstract Classes and Methods
          • Practical Application of OOP
          • Double Under (Dunder) Methods
          • Python Script Files
          • Python Files
          • Understanding the if __name__ == '__main__' Syntax
        • File IO and Exception Handling
          • Exception Handling
          • File IO
          • File IO with Exception Handling
          • OS Module
          • argv Command Line Arguments and the re Module
        • Misc Stuff and Q&A
    • IDE
      • Virtual Studio Code
        • Cheatsheet
    • Postman
      • Postman Overview
      • Create a GET HTTP request
      • HTTP Requests
      • Saving Postman requests
      • Environment Variables
  • Virtualization
    • Proxmox
      • Proxmox Cheatsheet
      • Proxmox Common Errors
      • Install Home Assistant in Proxmox via script
      • Create cloud-init template
      • Install guest-agent on new VM
      • Proxmox post install script
  • Webservers
    • Apache
      • Redirect 301 - Apache to index.html
    • Glassfish
      • Redirect 301 Glassfish
    • Tomcat
      • Useful tomcat files
  • Storage
    • NetApp
      • Netapp Overview
      • How to create symlinks
    • Nextcloud
      • Nextcloud Snap install and S3 Storage Bucket
      • Nextcloud Fail2Ban Regex
      • Set up OnlyOffice on Nextcloud
      • Set up Joplin and CalDav on Nextcloud
  • Software
    • Ansys
      • Ansys missing libraries
      • Ansys install
    • Jboss
      • Jboss process not working
Powered by GitBook
On this page
  • Conceptual Questions:
  • 1. What is a data structure?
  • 2. What is an Array?
  • 3. What is a Linked List?
  • 4. What is a Stack?
  • 5. What is LIFO?
  • 6. What is a Queue?
  • 7. What is FIFO?
  • 8. What are binary trees?
  • 9. What is Recursion?
  • 10. What is the OOPs concept?
  • 11. What are the concepts introduced in OOPs?
  • 12. Explain Binary Search Tree?
  • 13. Explain Doubly Linked Lists?
  • 14. What is a Graph?
  • 15. Differentiate between linear and non-linear data structure?
  • 16. What is a deque?
  • 17. What is the difference between Stack and Array?
  • 18. What sorting algorithm is the best?
  • 19. How does variable declaration affect memory?
  • 20. What are dynamic data structures?
  • Programming Interview Questions:
  • 1. How do you reserve a string in Java?
  • 2. How do you determine if a string is palidrome?
  • 3. Find the number of occurances of a character in a string?
  • 4. Find if the given two strings are anagrams or not?
  • 5. How do you calculate the number of vowels and consonants in a String?
  • 6. How do you get the matching elements in an integer array?
  • 7. Code the Bubble Sort algorithm?
  • 8. Code the Insertion Sort algorithm?
  • 9. How to reverse an array?
  • 10. Swap two numbers without using a third variable
  • 11. Print a Fibonacci series using recurison?
  • 12. How do you find the factorial of a number?
  • 13. Reverse a linked list?
  • 14. How do you implement Binary Search?
  • 15. Find the second largest number in an array?
  • 16. How do you remove all occurances of a given character from the input string?
  • 17. Showcase Inheritance with the help of a program?
  • 18. Explain overloading and overriding with the help of a program?
  • 19. Check if the given number is prime?
  • 20. Sum up all elements in an array
  1. Programming
  2. Interview Questions & Answers

General Programming Questions

Conceptual Questions:

1. What is a data structure?

A data structure is a storage format that defines the way data is stored, organized and manipulated

Examples:

  • Array

  • Trees

  • Graphs

2. What is an Array?

  • An array is a collection of items stored at contiguous memory locations

  • Items stored are the same type

3. What is a Linked List?

A linked list, like an array, is linear data structured in which the elements are not necessary stored in a contiguous manner

  • It is basically a sequence of nodes, each node points towards the next node forming a chain-like structure

4. What is a Stack?

Stack is a linear data structure that performs operations in a LIFO (Last in first out) order

  • In a stack, elements can only be accessed starting from the topmost to the bottom element

5. What is LIFO?

LIFO stands for Last in First Out

It is a way of accessing, storing and retrieving data

6. What is a Queue?

A Queue is a linear data structure that performs operations in a FIFO (First in first Out) order

7. What is FIFO?

FIFO stands for First In First Out

  • It's a way of accessing, storing and retrieving data

  • The data that was stored first is extracted first

8. What are binary trees?

Binary trees are an extension of the linked list structured

  • Binary tree has two nodes at all times, a left node and a right node

9. What is Recursion?

Recursion refers to a function calling itself based on a terminating condition

It uses LIFO and therefor makes use of the stack data structure

10. What is the OOPs concept?

Stands for Object Oriented Programming System which is a paradigm that provides concepts such as objects, classes, inheritance, among others

11. What are the concepts introduced in OOPs?

The concepts introduce in OOPs are:

  • Object: A real-world entity having a particular state and behavior. It can be defined as an instance of a class

  • Class: A logical entity that defines the blueprint from which an object can be created or instantiated

  • Inheritance: A concept that refers to an object acquiring all the properties and behavior of a parent object. It provides code re-usability

  • Polymorphism: A concept that allows a task to be performed in different ways. In Java, we use method overloading and method overriding to achive polymorphism

  • Abstraction: A concept that hides the internal details of an application and only shows the functionality. In Java, we use abstract class and interface to achive abstraction

  • Encapsulation: A concept that refers t the wrapping of code and data together into a single unit

12. Explain Binary Search Tree?

A binary search tree stores data in such a way that it can be retrieved very efficiently

  • The left subtree contains nodes whose keys are less or equal than the node's key value

  • The right subtree contains nodes whose keys are greater than the node's key value

13. Explain Doubly Linked Lists?

Doubly linked lists are a special type of linked list in which traversal across the data elements can be done in both directions

  • This is made possible by having two links in every node, one that links to the next node and another that connects to the previous node

14. What is a Graph?

A graph is one type of data structure that contains a set of ordered pairs

  • These ordered pairs are also referred to as edges or arcs and are used to connect nodes where data can be stored and retrieved

15. Differentiate between linear and non-linear data structure?

16. What is a deque?

Is a double-ended queue

  • This is a structure in which elements can be inserted or removed from either end:

17. What is the difference between Stack and Array?

18. What sorting algorithm is the best?

There are many types of sorting algorithms:

  • quick sort

  • bubble sort

  • balloon sort

  • radix sort

  • merge sort

  • etc...

No algorithm can be considered as the best or fastest because each is designed for a specific type of data structure where it performs the best

19. How does variable declaration affect memory?

The amount of memory to be allocated or reserved depends on the data type being stored in that variable

Example: A variable is declared to be INTEGER type then 32 bits of memory storage will be reserved for that variable.

20. What are dynamic data structures?

Dynamic data structures are structures that expand and contract as a program runs

  • It provides a flexible means of manipulating data because it can adjust according to the size of the data

Programming Interview Questions:

1. How do you reserve a string in Java?

2. How do you determine if a string is palidrome?

Reverse the string and compare it to the original string. If they are equal then it is palidrome

3. Find the number of occurances of a character in a string?

Java:

  1. Define a count as INT

  2. Define search word

  3. for loop through each character

  4. in loop if character = search character then count = count + 1

  5. print count

Python:

count = 0
for words in wird_dict.key():
	count = int(count) + 1
print count

4. Find if the given two strings are anagrams or not?

Two strings are anagrams if they contain a similar group of characters in a carried sequence

Python:

# function to check if two strings are anagrams or not
def check(s1, s2):
	# the sorted strings are checked
	if(sorted(s1) == sorted(s2)):
		print("The strings are anagrams")
	else:
		print("The strings are not anagrams")

# deliver code
s1 = "listen"
s2 = "silent"
check(s1, s2)

5. How do you calculate the number of vowels and consonants in a String?

Python:

original = raw_input('Enter a word: ')
word = original.lower()
first = word[0]

if len(original) > 0 and original.isalpha():
	if first == "a" or "e" or "i" or "u":
		print "vowel"
	else:
		print "consonant"
else:
	print "empty"

6. How do you get the matching elements in an integer array?

Java:

  1. Define an INT array

  2. Nest couple of loops where you compare the numbers against all other numbers

  3. if condition to print if it does find 2 numbers matching

7. Code the Bubble Sort algorithm?

Java:

  1. Declare array

  2. Nest couple of loops to compare the numbers

  3. Then sort the array will be sorted in the ascending order if found in any other order

Python:

# Python program for implementation of Bubble Sort
def bubbleSort(arr):
    n = len(arr)
  
    # Traverse through all array elements
    for i in range(n-1):
    # range(n) also work but outer loop will repeat one time more than needed.
  
        # Last i elements are already in place
        for j in range(0, n-i-1):
  
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
  
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
  
bubbleSort(arr)
  
print ("Sorted array is:")
for i in range(len(arr)):
    print ("% d" % arr[i]), 

8. Code the Insertion Sort algorithm?

Python:

# Python program for implementation of Insertion Sort

# Function to do insertion sort
def insertionSort(arr):
  
    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):
  
        key = arr[i]
  
        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >=0 and key < arr[j] :
                arr[j+1] = arr[j]
                j -= 1
        arr[j+1] = key
  
  
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
    print ("%d" %arr[i])

9. How to reverse an array?

Python:

Using List Slicing to Reverse an Array in Python:

#The original array
arr = [11, 22, 33, 44, 55]
print("Array is :",arr)
 
res = arr[::-1] #reversing using list slicing
print("Resultant new reversed array:",res)

Output:

Array is : [1, 2, 3, 4, 5]
Resultant new reversed array: [5, 4, 3, 2, 1]

Using reverse() Method

#The original array
arr = [11, 22, 33, 44, 55]
print("Before reversal Array is :",arr)
 
arr.reverse() #reversing using reverse()
print("After reversing Array:",arr)

Output:

Before reversal Array is : [11, 22, 33, 44, 55]
After reversing Array: [55, 44, 33, 22, 11]

10. Swap two numbers without using a third variable

a = 10
b = 20

b = b + a
a = b - a
b = b - a

11. Print a Fibonacci series using recurison?

# Python program to display the Fibonacci sequence
def recur_fibo(n):
	if n <= 1:
      	return n
	else:
      	return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid
if nterms <= 0:
  	print("Plese enter a positive integer")
else:
  	print("Fibonacci sequence:")
   	for i in range(nterms):
    	print(recur_fibo(i))

12. How do you find the factorial of a number?

# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
  	print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   	print("The factorial of 0 is 1")
else:
   	for i in range(1,num + 1):
      	factorial = factorial*i
   	print("The factorial of",num,"is",factorial)

13. Reverse a linked list?

# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next'
#variable is getting created in each loop.
 
# Node class
 
 
class Node:
 
    # Constructor to initialize the node object
    def __init__(self, data):
        self.data = data
        self.next = None
 
 
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # Function to reverse the linked list
    def reverse(self):
        prev = None
        current = self.head
        while(current is not None):
            next = current.next
            current.next = prev
            prev = current
            current = next
        self.head = prev
 
    # Function to insert a new node at the beginning
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
 
    # Utility function to print the linked LinkedList
    def printList(self):
        temp = self.head
        while(temp):
            print temp.data,
            temp = temp.next
 
 
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
 
print "Given Linked List"
llist.printList()
llist.reverse()
print "\nReversed Linked List"
llist.printList()

14. How do you implement Binary Search?

# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
 
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
 
    # Check base case
    if high >= low:
 
        mid = (high + low) // 2
 
        # If element is present at the middle itself
        if arr[mid] == x:
            return mid
 
        # If element is smaller than mid, then it can only
        # be present in left subarray
        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)
 
        # Else the element can only be present in right subarray
        else:
            return binary_search(arr, mid + 1, high, x)
 
    else:
        # Element is not present in the array
        return -1
 
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
 
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
 
if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")

15. Find the second largest number in an array?

import array
arr = []
n = int(input("enter size of array : "))
for x in range(n):
    x=int(input("enter element of array : "))
    arr.append(x)
 
sorted_array = sorted(array.array('i', arr))
for i in range(len(arr)-1, 0, -1):
    if sorted_array[i]!=sorted_array[i-1]:
        print(f"second largest element is {sorted_array[i-1]}")
        break 

16. How do you remove all occurances of a given character from the input string?

a = "Australia"
a = a.replace("a", "");
print a

17. Showcase Inheritance with the help of a program?

class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])

18. Explain overloading and overriding with the help of a program?

Overloading: When a class has two or more methods with the same name they are called overloaded methods

Overriding: When a superclass method is also implemented in the child class, it's a case of overriding

19. Check if the given number is prime?

# Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable
flag = False

# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")

20. Sum up all elements in an array

# Python program for sum of the array elements

# functions to find sum of elements

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

# main function
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    print ('sum_1: {}'.format(sum_1(arr)))
    print ('sum_2: {}'.format(sum_2(arr)))
PreviousInterview Questions & AnswersNextPython Interview Questions Beginner

Last updated 2 years ago