Python Coding Interview Questions and Answers
Ques 16. 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 17. 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 18. 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:
Ques 19. 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 20. 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 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.
- Write a Python program to count the occurrences of each element in a list.