Python Coding Interview Questions and Answers
Intermediate / 1 to 5 years experienced level questions & answers
Ques 1. Write a Python program to find the factorial of a number.
def factorial(n):
return 1 if n == 0 else n * factorial(n-1)
Example:
Ques 2. Implement a function to check if a number is prime.
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
Example:
Ques 3. Create a Python class for a basic stack implementation.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
Example:
stack.push(1)
stack.push(2)
print(stack.pop()) # Output: 2
Ques 4. Write a Python program to find the nth Fibonacci number.
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Example:
Ques 5. Write a Python program to find the length of the longest increasing subsequence in an array.
def longest_increasing_subsequence(arr):
n = len(arr)\n lis = [1]*n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
return max(lis)
Example:
Ques 6. Create a Python generator function to generate the power set of a given set.
def power_set(input_set):
n = len(input_set)
for i in range(1 << n):
subset = [input_set[j]
for j in range(n):
if (i & (1 << j)) > 0]
yield subset
Example:
Ques 7. Write a Python function to implement the binary search algorithm.
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Example:
Most helpful rated by users:
- Implement a function to find the maximum element in a list.
- Write a Python program to count the occurrences of each element in a list.
Related interview subjects
COBOL interview questions and answers - Total 50 questions |
R Language interview questions and answers - Total 30 questions |
Python Coding interview questions and answers - Total 20 questions |
Scala interview questions and answers - Total 48 questions |
Swift interview questions and answers - Total 49 questions |
Golang interview questions and answers - Total 30 questions |
Embedded C interview questions and answers - Total 30 questions |
C++ interview questions and answers - Total 142 questions |
VBA interview questions and answers - Total 30 questions |