Python Coding Interview Questions and Answers
Experienced / Expert level questions & answers
Ques 1. Implement a function to find the intersection of two lists.
def intersection(list1, list2):
return list(set(list1) & set(list2))
Example:
Ques 2. Write a Python program to perform matrix multiplication.
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2)
Example:
# Output: [[19, 22], [43, 50]]
Ques 3. Create a generator function to generate Fibonacci numbers.
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
Example:
print(next(fib_gen)) # Output: 0
Ques 4. Implement a depth-first search (DFS) algorithm for a graph.
def dfs(graph, node, visited):
if node not in visited:
print(node)
visited.add(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
Example:
visited_set = set()
dfs(graph, 1, visited_set)
Ques 5. Implement a function to check if a binary tree is balanced.
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_balanced(root):
if root is None:
return True
left_height = height(root.left)
right_height = height(root.right)
return abs(left_height - right_height) <= 1 and is_balanced(root.left) and is_balanced(root.right)
def height(node):
if node is None:
return 0
return max(height(node.left), height(node.right)) + 1
Example:
is_balanced(root)
Ques 6. Write a Python program to implement a simple LRU (Least Recently Used) cache.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacitydef get(self, key):
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1def put(self, key, value):
if len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
self.cache.move_to_end(key)
Example:
lru_cache = LRUCache(3)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
lru_cache.put(3, 3)
print(lru_cache.get(2)) # Output: 2
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.
- Write a function to reverse a string.
- Implement a function to check if a string is a palindrome.
- Write a Python function to check if a given year is a leap year.
Related interview subjects
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 |
COBOL interview questions and answers - Total 50 questions |
R Language interview questions and answers - Total 30 questions |