Top 100 Python Interview Programs with Answers

Top 100 Python Interview Programs with Answers

 

1. Print “Hello, World!” in Python.

print("Hello, World!")

2. Calculate the sum of two numbers.

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

sum = num1 + num2

print("Sum:", sum)

3. Swap two variables without using a temporary variable.

a = 5

b = 10

a, b = b, a

print("a:", a)

print("b:", b)

4. Find the factorial of a number.

def factorial(n):

    if n == 0:

        return 1

    else:

        return n * factorial(n - 1)

 

num = int(input("Enter a number: "))

print("Factorial:", factorial(num))

5. Check if a number is prime.

def is_prime(n):

    if n <= 1:

        return False

    for i in range(2, int(n ** 0.5) + 1):

        if n % i == 0:

            return False

    return True

 

num = int(input("Enter a number: "))

if is_prime(num):

    print(num, "is prime.")

else:

    print(num, "is not prime.")

6. Check if a string is a palindrome.

def is_palindrome(s):

    s = s.lower().replace(" ", "")

    return s == s[::-1]

 

string = input("Enter a string: ")

if is_palindrome(string):

    print("Palindrome")

else:

    print("Not a palindrome")

7. Count the occurrences of a character in a string.

def count_occurrences(string, char):

    count = 0

    for c in string:

        if c == char:

            count += 1

    return count

 

string = input("Enter a string: ")

char = input("Enter a character: ")

print("Occurrences:", count_occurrences(string, char))

8. Remove duplicates from a list.

def remove_duplicates(lst):

    return list(set(lst))

 

my_list = [1, 2, 2, 3, 4, 4, 5]

result = remove_duplicates(my_list)

print("List with duplicates removed:", result)

9. Find the largest element in an array.

def find_largest_element(arr):

    max_element = arr[0]

    for num in arr:

        if num > max_element:

            max_element = num

    return max_element

 

array = [12, 45, 78, 23, 56]

print("Largest element:", find_largest_element(array))

10. Implement a basic calculator.

def add(x, y):

    return x + y

 

def subtract(x, y):

    return x - y

 

def multiply(x, y):

    return x * y

 

def divide(x, y):

    return x / y

 

print("Select operation:")

print("1. Add")

print("2. Subtract")

print("3. Multiply")

print("4. Divide")

 

choice = input("Enter choice (1/2/3/4): ")

 

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

 

if choice == '1':

    print("Result:", add(num1, num2))

elif choice == '2':

    print("Result:", subtract(num1, num2))

elif choice == '3':

    print("Result:", multiply(num1, num2))

elif choice == '4':

    print("Result:", divide(num1, num2))

else:

    print("Invalid input")

11. Implement a stack using a list.

class Stack:

    def __init__(self):

        self.items = []

 

    def push(self, item):

        self.items.append(item)

 

    def pop(self):

        if not self.is_empty():

            return self.items.pop()

        else:

            return None

 

    def is_empty(self):

        return len(self.items) == 0

 

    def peek(self):

        if not self.is_empty():

            return self.items[-1]

        else:

            return None

 

stack = Stack()

stack.push(1)

stack.push(2)

stack.push(3)

 

print("Top element:", stack.peek())

print("Popped:", stack.pop())

print("Top element:", stack.peek())

12. Implement a queue using a list.

class Queue:

    def __init__(self):

        self.items = []

 

    def enqueue(self, item):

        self.items.append(item)

 

    def dequeue(self):

        if not self.is_empty():

            return self.items.pop(0)

        else:

            return None

 

    def is_empty(self):

        return len(self.items) == 0

 

    def front(self):

        if not self.is_empty():

            return self.items[0]

        else:

            return None

 

queue = Queue()

queue.enqueue(1)

queue.enqueue(2)

queue.enqueue(3)

 

print("Front element:", queue.front())

print("Dequeued:", queue.dequeue())

print("Front element:", queue.front())

13. Reverse a string.

def reverse_string(s):

    return s[::-1]

 

input_string = input("Enter a string: ")

reversed_string = reverse_string(input_string)

print("Reversed string:", reversed_string)

14. Find the maximum subarray sum.

def max_subarray_sum(arr):

    max_sum = current_sum = arr[0]

    for num in arr[1:]:

        current_sum = max(num, current_sum + num)

        max_sum = max(max_sum, current_sum)

    return max_sum

 

array = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

print("Maximum subarray sum:", max_subarray_sum(array))

15. Implement binary search.

def binary_search(arr, target):

    left, right = 0, len(arr) - 1

    while left <= right:

        mid = (left + right) // 2

        if arr[mid] == target:

            return mid

        elif arr[mid] < target:

            left = mid + 1

        else:

            right = mid - 1

    return -1

 

array = [1, 3, 5, 7, 9, 11, 13, 15, 17]

target = 7

result = binary_search(array, target)

if result != -1:

    print(f"Element {target} found at index {result}")

else:

    print(f"Element {target} not found")

16. Implement selection sort.

def selection_sort(arr):

    for i in range(len(arr)):

        min_index = i

        for j in range(i + 1, len(arr)):

            if arr[j] < arr[min_index]:

                min_index = j

        arr[i], arr

 

[min_index] = arr[min_index], arr[i]

 

array = [64, 34, 25, 12, 22, 11, 90]

selection_sort(array)

print("Sorted array:", array)

17. Implement insertion sort.

def insertion_sort(arr):

    for i in range(1, len(arr)):

        key = arr[i]

        j = i - 1

        while j >= 0 and arr[j] > key:

            arr[j + 1] = arr[j]

            j -= 1

        arr[j + 1] = key

 

array = [64, 34, 25, 12, 22, 11, 90]

insertion_sort(array)

print("Sorted array:", array)

18. Implement merge sort.

def merge_sort(arr):

    if len(arr) > 1:

        mid = len(arr) // 2

        left_half = arr[:mid]

        right_half = arr[mid:]

 

        merge_sort(left_half)

        merge_sort(right_half)

 

        i = j = k = 0

 

        while i < len(left_half) and j < len(right_half):

            if left_half[i] < right_half[j]:

                arr[k] = left_half[i]

                i += 1

            else:

                arr[k] = right_half[j]

                j += 1

            k += 1

 

        while i < len(left_half):

            arr[k] = left_half[i]

            i += 1

            k += 1

 

        while j < len(right_half):

            arr[k] = right_half[j]

            j += 1

            k += 1

 

array = [64, 34, 25, 12, 22, 11, 90]

merge_sort(array)

print("Sorted array:", array)

19. Implement a linked list.

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

 

class LinkedList:

    def __init__(self):

        self.head = None

 

    def append(self, data):

        new_node = Node(data)

        if not self.head:

            self.head = new_node

        else:

            current = self.head

            while current.next:

                current = current.next

            current.next = new_node

 

    def display(self):

        current = self.head

        while current:

            print(current.data, end=" -> ")

            current = current.next

        print("None")

 

linked_list = LinkedList()

linked_list.append(1)

linked_list.append(2)

linked_list.append(3)

 

linked_list.display()

20. Detect a cycle in a linked list.

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

 

class LinkedList:

    def __init__(self):

        self.head = None

 

    def append(self, data):

        new_node = Node(data)

        if not self.head:

            self.head = new_node

        else:

            current = self.head

            while current.next:

                current = current.next

            current.next = new_node

 

    def create_cycle(self, pos):

        if pos == -1:

            return

        current = self.head

        start_node = None

        count = 0

        while current.next:

            if count == pos:

                start_node = current

            current = current.next

            count += 1

        current.next = start_node

 

    def has_cycle(self):

        slow = fast = self.head

        while fast and fast.next:

            slow = slow.next

            fast = fast.next.next

            if slow == fast:

                return True

        return False

 

linked_list = LinkedList()

linked_list.append(1)

linked_list.append(2)

linked_list.append(3)

linked_list.create_cycle(1)

 

if linked_list.has_cycle():

    print("Linked list has a cycle.")

else:

    print("Linked list does not have a cycle.")

21. Reverse a string.

def reverse_string(s):

    return s[::-1]

 

input_string = input("Enter a string: ")

reversed_string = reverse_string(input_string)

print("Reversed string:", reversed_string)

22. Count the occurrences of a substring in a string.

def count_substring_occurrences(main_string, substring):

    count = 0

    start = 0

    while start < len(main_string):

        pos = main_string.find(substring, start)

        if pos != -1:

            count += 1

            start = pos + 1

        else:

            break

    return count

 

main_string = input("Enter the main string: ")

substring = input("Enter the substring: ")

print("Occurrences:", count_substring_occurrences(main_string, substring))

23. Check if two strings are anagrams.

def are_anagrams(str1, str2):

    return sorted(str1) == sorted(str2)

 

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

if are_anagrams(string1, string2):

    print("Strings are anagrams.")

else:

    print("Strings are not anagrams.")

24. Remove duplicates from a string.

def remove_duplicates(s):

    result = ""

    for char in s:

        if char not in result:

            result += char

    return result

 

input_string = input("Enter a string: ")

result = remove_duplicates(input_string)

print("String with duplicates removed:", result)

25. Capitalize the first letter of each word in a sentence.

def capitalize_words(sentence):

    words = sentence.split()

    capitalized_words = [word.capitalize() for word in words]

    return " ".join(capitalized_words)

 

input_sentence = input("Enter a sentence: ")

capitalized_sentence = capitalize_words(input_sentence)

print("Capitalized sentence:", capitalized_sentence)

26. Implement a basic text search (substring search) algorithm.

def substring_search(text, pattern):

    n = len(text)

    m = len(pattern)

    for i in range(n - m + 1):

        j = 0

        while j < m:

            if text[i + j] != pattern[j]:

                break

            j += 1

        if j == m:

            return i

    return -1

 

text = input("Enter the text: ")

pattern = input("Enter the pattern to search: ")

index = substring_search(text, pattern)

if index != -1:

    print(f"Pattern found at index {index}")

else:

    print("Pattern not found")

  1. Find the second largest element in a list:

def second_largest(lst):

    if len(lst) < 2:

        return None

    largest = second = float('-inf')

    for num in lst:

        if num > largest:

            second = largest

            largest = num

        elif num > second and num != largest:

            second = num

    return second

 

# Example usage

numbers = [10, 5, 8, 20, 15]

print("Second largest:", second_largest(numbers))

  1. Find the intersection of two lists:

def intersection(lst1, lst2):

    return list(set(lst1) & set(lst2))

 

# Example usage

list1 = [1, 2, 3, 4, 5]

list2 = [3, 4, 5, 6, 7]

print("Intersection:", intersection(list1, list2))

  1. Remove all occurrences of an element from a list:

def remove_all(lst, value):

    return [x for x in lst if x != value]

 

# Example usage

numbers = [1, 2, 3, 2, 4, 2, 5]

value_to_remove = 2

print("List after removal:", remove_all(numbers, value_to_remove))

  1. Rotate a list to the right by K steps:

def rotate_right(lst, k):

    if not lst:

        return []

    k %= len(lst)

    return lst[-k:] + lst[:-k]

 

# Example usage

numbers = [1, 2, 3, 4, 5]

k = 2

print("Rotated list:", rotate_right(numbers, k))

  1. Count the frequency of elements in a list using a dictionary:

def count_frequency(lst):

    freq_dict = {}

    for item in lst:

        freq_dict[item] = freq_dict.get(item, 0) + 1

    return freq_dict

 

# Example usage

numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

print("Frequency:", count_frequency(numbers))

  1. Find the common elements in two lists using sets:

def common_elements(lst1, lst2):

    set1 = set(lst1)

    set2 = set(lst2)

    return list(set1 & set2)

 

# Example usage

list1 = [1, 2, 3, 4, 5]

list2 = [3, 4, 5, 6, 7]

print("Common elements:", common_elements(list1, list2))

  1. Convert a list of tuples into a dictionary:

def list_to_dict(lst):

    return {key: value for key, value in lst}

 

# Example usage

data = [("a", 1), ("b", 2), ("c", 3)]

print("Dictionary:", list_to_dict(data))

  1. Remove keys from a dictionary while iterating over it:

def remove_keys(dictionary, keys_to_remove):

    for key in keys_to_remove:

        dictionary.pop(key, None)

 

# Example usage

data = {"a": 1, "b": 2, "c": 3}

keys_to_remove = ["a", "c"]

remove_keys(data, keys_to_remove)

print("Modified dictionary:", data)

  1. Implement factorial using recursion:

def factorial(n):

    if n == 0:

        return 1

    return n * factorial(n - 1)

 

# Example usage

number = 5

print("Factorial:", factorial(number))

  1. Implement Fibonacci series using recursion:

def fibonacci(n):

    if n <= 1:

        return n

    return fibonacci(n - 1) + fibonacci(n - 2)

 

# Example usage

n_terms = 6

fib_series = [fibonacci(i) for i in range(n_terms)]

print("Fibonacci series:", fib_series)

  1. Calculate the power of a number using recursion:

def power(base, exponent):

    if exponent == 0:

        return 1

    return base * power(base, exponent - 1)

 

# Example usage

base = 2

exponent = 3

print("Power:", power(base, exponent))

  1. Implement the Tower of Hanoi problem using recursion:

def tower_of_hanoi(n, source, auxiliary, target):

    if n > 0:

        tower_of_hanoi(n - 1, source, target, auxiliary)

        print(f"Move disk {n} from {source} to {target}")

        tower_of_hanoi(n - 1, auxiliary, source, target)

 

# Example usage

num_disks = 3

tower_of_hanoi(num_disks, 'A', 'B', 'C')

  1. Create a class and instantiate an object:

class Car:

    def __init__(self, make, model):

        self.make = make

        self.model = model

 

car1 = Car("Toyota", "Camry")

print("Car:", car1.make, car1.model)

  1. Implement inheritance with classes:

class Vehicle:

    def __init__(self, make):

        self.make = make

 

class Car(Vehicle):

    def __init__(self, make, model):

        super().__init__(make)

        self.model = model

 

car = Car("Toyota", "Camry")

print("Car:", car.make, car.model)

  1. Implement method overriding and overloading:

class Parent:

    def show(self, x):

        print("Parent:", x)

 

class Child(Parent):

    def show(self, x, y):

        print("Child:", x, y)

 

child = Child()

child.show(10)        # This will raise an error since method is not overloaded

child.show(10, 20)    # This will print "Child: 10 20"

  1. Create a basic exception class and handle exceptions:

class MyError(Exception):

    def __init__(self, message):

        self.message = message

 

try:

    raise MyError("This is a custom exception.")

except MyError as e:

    print("Caught an exception:", e.message)

  1. Read from and write to a text file:

# Writing to a file

with open("example.txt", "w") as f:

    f.write("Hello, World!")

 

# Reading from a file

with open("example.txt", "r") as f:

    content = f.read()

    print("File content:", content)

  1. Copy the contents of one file to another:

def copy_file(source, destination):

    with open(source, "r") as src_file, open(destination, "w") as dest_file:

        dest_file.write(src_file.read())

 

source_file = "source.txt"

destination_file = "destination.txt"

copy_file(source_file, destination_file)

  1. Count the number of lines, words, and characters in a

file:

def count_file_stats(filename):

    with open(filename, "r") as f:

        content = f.read()

        lines = content.count("\n") + 1

        words = len(content.split())

        characters = len(content)

    return lines, words, characters

 

file_name = "example.txt"

lines, words, characters = count_file_stats(file_name)

print("Lines:", lines)

print("Words:", words)

print("Characters:", characters)

  1. Implement binary search:

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 usage

sorted_array = [1, 3, 5, 7, 9, 11, 13]

target = 7

print("Index:", binary_search(sorted_array, target))

  1. Implement bubble sort:

def bubble_sort(arr):

    n = len(arr)

    for i in range(n):

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]

 

# Example usage

numbers = [64, 34, 25, 12, 22, 11, 90]

bubble_sort(numbers)

print("Sorted array:", numbers)

  1. Implement quick sort:

def quick_sort(arr):

    if len(arr) <= 1:

        return arr

    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]

    middle = [x for x in arr if x == pivot]

    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)

 

# Example usage

numbers = [64, 34, 25, 12, 22, 11, 90]

sorted_numbers = quick_sort(numbers)

print("Sorted array:", sorted_numbers)

  1. Implement a basic search algorithm (linear search):

def linear_search(arr, target):

    for i in range(len(arr)):

        if arr[i] == target:

            return i

    return -1

 

# Example usage

numbers = [64, 34, 25, 12, 22, 11, 90]

target = 22

print("Index:", linear_search(numbers, target))

  1. Implement a solution for the Fibonacci sequence using dynamic programming:

def fibonacci_dynamic(n):

    fib = [0] * (n + 1)

    fib[1] = 1

    for i in range(2, n + 1):

        fib[i] = fib[i - 1] + fib[i - 2]

    return fib[n]

 

# Example usage

n = 6

print("Fibonacci:", fibonacci_dynamic(n))

  1. Find the longest common subsequence of two strings:

def longest_common_subsequence(str1, str2):

    m, n = len(str1), len(str2)

    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):

        for j in range(1, n + 1):

            if str1[i - 1] == str2[j - 1]:

                dp[i][j] = dp[i - 1][j - 1] + 1

            else:

                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]

 

# Example usage

string1 = "AGGTAB"

string2 = "GXTXAYB"

print("Longest common subsequence:", longest_common_subsequence(string1, string2))

  1. Implement the knapsack problem using dynamic programming:

def knapsack_dynamic(weights, values, capacity):

    n = len(weights)

    dp = [[0] * (capacity + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):

        for w in range(1, capacity + 1):

            if weights[i - 1] <= w:

                dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])

            else:

                dp[i][w] = dp[i - 1][w]

    return dp[n][capacity]

 

# Example usage

weights = [2, 3, 4, 5]

values = [3, 4, 5, 6]

capacity = 5

print("Maximum value:", knapsack_dynamic(weights, values, capacity))

  1. Implement a graph using an adjacency matrix or list:

class Graph:

    def __init__(self, vertices):

        self.vertices = vertices

        self.graph = [[] for _ in range(vertices)]

   

    def add_edge(self, u, v):

        self.graph[u].append(v)

   

    def print_graph(self):

        for i in range(self.vertices):

            print("Vertex", i, ":", self.graph[i])

 

# Example usage

g = Graph(4)

g.add_edge(0, 1)

g.add_edge(0, 2)

g.add_edge(1, 2)

g.add_edge(2, 0)

g.add_edge(2, 3)

g.add_edge(3, 3)

g.print_graph()

  1. Perform depth-first search (DFS) on a graph:

class Graph:

    def __init__(self, vertices):

        self.vertices = vertices

        self.graph = [[] for _ in range(vertices)]

   

    def add_edge(self, u, v):

        self.graph[u].append(v)

   

    def dfs_util(self, v, visited):

        visited[v] = True

        print(v, end=" ")

        for i in self.graph[v]:

            if not visited[i]:

                self.dfs_util(i, visited)

   

    def dfs(self, start_vertex):

        visited = [False] * self.vertices

        self.dfs_util(start_vertex, visited)

 

# Example usage

g = Graph(4)

g.add_edge(0, 1)

g.add_edge(0, 2)

g.add_edge(1, 2)

g.add_edge(2, 0)

g.add_edge(2, 3)

g.add_edge(3, 3)

print("DFS:", end=" ")

g.dfs(2)

  1. Perform breadth-first search (BFS) on a graph:

from collections import deque

 

class Graph:

    def __init__(self, vertices):

        self.vertices = vertices

        self.graph = [[] for _ in range(vertices)]

   

    def add_edge(self, u, v):

        self.graph[u

 

].append(v)

   

    def bfs(self, start_vertex):

        visited = [False] * self.vertices

        queue = deque()

        queue.append(start_vertex)

        visited[start_vertex] = True

        while queue:

            vertex = queue.popleft()

            print(vertex, end=" ")

            for i in self.graph[vertex]:

                if not visited[i]:

                    queue.append(i)

                    visited[i] = True

 

# Example usage

g = Graph(4)

g.add_edge(0, 1)

g.add_edge(0, 2)

g.add_edge(1, 2)

g.add_edge(2, 0)

g.add_edge(2, 3)

g.add_edge(3, 3)

print("BFS:", end=" ")

g.bfs(2)

  1. Find the shortest path between two nodes in a graph:

from collections import defaultdict

 

class Graph:

    def __init__(self):

        self.graph = defaultdict(list)

   

    def add_edge(self, u, v, w):

        self.graph[u].append((v, w))

   

    def dijkstra(self, start_vertex):

        distances = {vertex: float('inf') for vertex in self.graph}

        distances[start_vertex] = 0

        priority_queue = [(0, start_vertex)]

       

        while priority_queue:

            current_distance, current_vertex = heapq.heappop(priority_queue)

           

            if current_distance > distances[current_vertex]:

                continue

           

            for neighbor, weight in self.graph[current_vertex]:

                distance = current_distance + weight

                if distance < distances[neighbor]:

                    distances[neighbor] = distance

                    heapq.heappush(priority_queue, (distance, neighbor))

       

        return distances

 

# Example usage

g = Graph()

g.add_edge('A', 'B', 1)

g.add_edge('A', 'C', 4)

g.add_edge('B', 'C', 2)

g.add_edge('B', 'D', 5)

g.add_edge('C', 'D', 1)

g.add_edge('D', 'A', 3)

start_vertex = 'A'

distances = g.dijkstra(start_vertex)

print("Shortest distances:", distances)

  1. Implement a binary search tree (BST):

class Node:

    def __init__(self, key):

        self.left = None

        self.right = None

        self.val = key

 

class BinarySearchTree:

    def __init__(self):

        self.root = None

   

    def insert(self, root, key):

        if root is None:

            return Node(key)

        if key < root.val:

            root.left = self.insert(root.left, key)

        else:

            root.right = self.insert(root.right, key)

        return root

   

    def inorder_traversal(self, root):

        if root:

            self.inorder_traversal(root.left)

            print(root.val, end=" ")

            self.inorder_traversal(root.right)

   

    def insert_key(self, key):

        self.root = self.insert(self.root, key)

   

    def inorder(self):

        self.inorder_traversal(self.root)

 

# Example usage

bst = BinarySearchTree()

keys = [50, 30, 20, 40, 70, 60, 80]

for key in keys:

    bst.insert_key(key)

bst.inorder()

  1. Perform in-order, pre-order, and post-order traversals on a tree:

class Node:

    def __init__(self, key):

        self.left = None

        self.right = None

        self.val = key

 

def inorder_traversal(root):

    if root:

        inorder_traversal(root.left)

        print(root.val, end=" ")

        inorder_traversal(root.right)

 

def preorder_traversal(root):

    if root:

        print(root.val, end=" ")

        preorder_traversal(root.left)

        preorder_traversal(root.right)

 

def postorder_traversal(root):

    if root:

        postorder_traversal(root.left)

        postorder_traversal(root.right)

        print(root.val, end=" ")

 

# Example usage

root = Node(1)

root.left = Node(2)

root.right = Node(3)

root.left.left = Node(4)

root.left.right = Node(5)

 

print("In-order:", end=" ")

inorder_traversal(root)

print("\nPre-order:", end=" ")

preorder_traversal(root)

print("\nPost-order:", end=" ")

postorder_traversal(root)

  1. Find the lowest common ancestor in a binary tree:

class Node:

    def __init__(self, key):

        self.left = None

        self.right = None

        self.val = key

 

def find_lca(root, node1, node2):

    if root is None:

        return None

   

    if root.val == node1 or root.val == node2:

        return root.val

   

    left_lca = find_lca(root.left, node1, node2)

    right_lca = find_lca(root.right, node1, node2)

   

    if left_lca and right_lca:

        return root.val

    return left_lca if left_lca else right_lca

 

# Example usage

root = Node(3)

root.left = Node(5)

root.right = Node(1)

root.left.left = Node(6)

root.left.right = Node(2)

root.right.left = Node(0)

root.right.right = Node(8)

root.left.right.left = Node(7)

root.left.right.right = Node(4)

 

node1 = 5

node2 = 1

lca = find_lca(root, node1, node2)

print("Lowest Common Ancestor:", lca)

  1. Check if a binary tree is balanced:

class Node:

    def __init__(self, key):

        self.left = None

        self.right = None

        self.val = key

 

def height(root):

    if root is None:

        return 0

    return max(height(root.left), height(root.right)) + 1

 

def is_balanced(root):

    if root is None:

        return True

   

    left_height = height(root.left)

    right_height = height(root.right)

   

    if abs(left_height - right_height) <= 1 and is_balanced(root.left) and is_balanced(root.right):

        return True

    return False

 

# Example usage

root = Node(1)

root.left = Node(2)

root.right = Node(3)

root.left.left = Node(4)

root.left.right = Node(5)

 

if is_balanced(root):

    print("Tree is balanced")

else:

    print("Tree is not balanced")

  1. Find the greatest common divisor (GCD) of two numbers:

def gcd(a, b):

    while b:

        a, b = b, a % b

    return a

 

# Example usage

num1 = 48

num2 = 18

print("GCD:", gcd(num1, num2))

  1. Find the least common multiple (LCM) of two numbers:

def lcm(a, b):

    return a * b // gcd(a, b)

 

# Example usage

num1 = 48

num2 = 18

print("LCM

 

:", lcm(num1, num2))

  1. Calculate the square root of a number:

def square_root(x):

    if x < 0:

        raise ValueError("Cannot calculate square root of a negative number")

    if x == 0:

        return 0

    guess = x

    epsilon = 1e-6

    while abs(guess * guess - x) > epsilon:

        guess = (guess + x / guess) / 2

    return guess

 

# Example usage

number = 25

print("Square root:", square_root(number))

  1. Implement Euclidean algorithm for finding GCD:

def euclidean_gcd(a, b):

    while b:

        a, b = b, a % b

    return a

 

# Example usage

num1 = 48

num2 = 18

print("GCD:", euclidean_gcd(num1, num2))

  1. Count the number of set bits (1s) in a binary representation:

def count_set_bits(n):

    count = 0

    while n:

        count += n & 1

        n >>= 1

    return count

 

# Example usage

number = 25

print("Number of set bits:", count_set_bits(number))

  1. Toggle a specific bit in a number:

def toggle_bit(n, position):

    mask = 1 << position

    return n ^ mask

 

# Example usage

number = 25

position = 3

result = toggle_bit(number, position)

print("Result:", result)

  1. Check if a number is a power of two:

def is_power_of_two(n):

    if n <= 0:

        return False

    return (n & (n - 1)) == 0

 

# Example usage

number = 16

print("Is power of two:", is_power_of_two(number))

 

68. Implement a basic multi-threading program:

import threading

 

def print_numbers():

    for i in range(1, 6):

        print(f"Number: {i}")

 

def print_letters():

    for letter in 'abcde':

        print(f"Letter: {letter}")

 

thread1 = threading.Thread(target=print_numbers)

thread2 = threading.Thread(target=print_letters)

 

thread1.start()

thread2.start()

 

thread1.join()

thread2.join()

 

print("Threads finished")

71. Validate an email address using regular expressions:

import re

 

def validate_email(email):

    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

    if re.match(pattern, email):

        return True

    else:

        return False

 

email = "example@email.com"

if validate_email(email):

    print("Valid email")

else:

    print("Invalid email")

73. Handle exceptions using try-except blocks:

try:

    num = int(input("Enter a number: "))

    result = 10 / num

    print("Result:", result)

except ZeroDivisionError:

    print("Cannot divide by zero")

except ValueError:

    print("Invalid input. Please enter a number.")

except Exception as e:

    print("An error occurred:", e)

75. Implement a simple function decorator:

def my_decorator(func):

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper

 

@my_decorator

def say_hello():

    print("Hello!")

 

say_hello()

77. Create a generator for Fibonacci numbers:

def fibonacci_generator():

    a, b = 0, 1

    while True:

        yield a

        a, b = b, a + b

 

fibonacci = fibonacci_generator()

for _ in range(10):

    print(next(fibonacci))

79. Create a Python module and import it in another script: File: mymodule.py

def greet(name):

    return f"Hello, {name}!"

File: main.py

import mymodule

 

message = mymodule.greet("Alice")

print(message)

81. Serialize and deserialize an object using the pickle module:

import pickle

 

data = {'name': 'Alice', 'age': 30}

 

# Serialize data

with open('data.pickle', 'wb') as f:

    pickle.dump(data, f)

 

# Deserialize data

with open('data.pickle', 'rb') as f:

    loaded_data = pickle.load(f)

 

print(loaded_data)

83. Create a simple HTTP server using the http.server module:

import http.server

import socketserver

 

PORT = 8000

 

Handler = http.server.SimpleHTTPRequestHandler

 

with socketserver.TCPServer(("", PORT), Handler) as httpd:

    print(f"Serving at port {PORT}")

    httpd.serve_forever()

85. Scrape data from a website using the BeautifulSoup library:

import requests

from bs4 import BeautifulSoup

 

url = "https://example.com"

response = requests.get(url)

soup = BeautifulSoup(response.content, "html.parser")

 

# Extract title

title = soup.title.string

print("Title:", title)

 

# Extract all links

for link in soup.find_all("a"):

    print("Link:", link.get("href"))

87. Connect to a SQLite database and perform basic CRUD operations:

import sqlite3

 

conn = sqlite3.connect("mydatabase.db")

cursor = conn.cursor()

 

# Create table

cursor.execute('''CREATE TABLE IF NOT EXISTS users

                  (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

 

# Insert data

cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))

conn.commit()

 

# Retrieve data

cursor.execute("SELECT * FROM users")

for row in cursor.fetchall():

    print("ID:", row[0], "Name:", row[1], "Age:", row[2])

 

conn.close()

89. Write unit tests using the unittest or pytest frameworks:

import unittest

 

def add(a, b):

    return a + b

 

class TestAddFunction(unittest.TestCase):

 

    def test_positive_numbers(self):

        result = add(2, 3)

        self.assertEqual(result, 5)

 

    def test_negative_numbers(self):

        result = add(-2, -3)

        self.assertEqual(result, -5)

 

if __name__ == '__main__':

    unittest.main()

91. Use the threading module to execute multiple functions concurrently:

import threading

 

def print_numbers():

    for i in range(1, 6):

        print(f"Number: {i}")

 

def print_letters():

    for letter in 'abcde':

        print(f"Letter: {letter}")

 

thread1 = threading.Thread(target=print_numbers)

thread2 = threading.Thread(target=print_letters)

 

thread1.start()

thread2.start()

 

thread1.join()

thread2.join()

 

print("Threads finished")

93. Explain the Singleton design pattern and implement it:

class Singleton:

    _instance = None

 

    def __new__(cls):

        if cls._instance is None:

            cls._instance = super().__new__(cls)

            cls._instance.value = None

        return cls._instance

 

singleton1 = Singleton()

singleton1.value = "Value 1"

 

singleton2 = Singleton()

print(singleton2.value)  # Output: "Value 1"

95. Explain how garbage collection works in Python: Garbage collection in Python is the process of automatically identifying and reclaiming memory occupied by objects that are no longer reachable or referenced in the program. Python uses a cyclic garbage collector that detects circular references and releases memory associated with them.

97. Optimize a slow-performing function using profiling tools: Profiling tools like cProfile can help identify performance bottlenecks in your code. Here’s a basic example:

import cProfile

 

def slow_function():

    total = 0

    for i in range(1000000):

        total += i

    return total

 

if __name__ == '__main__':

    profiler = cProfile.Profile()

    profiler.enable()

   

    result = slow_function()

   

    profiler.disable()

    profiler.print_stats(sort='cumulative')

99. Integrate with a REST API using the requests library:

import requests

 

url = "https://api.example.com/data"

headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}

 

response = requests.get(url, headers=headers)

 

if response.status_code == 200:

    data = response.json()

    # Process the data

else:

    print("Request failed

 

 with status code:", response.status_code)

 


Post a Comment

0 Comments