1.
Functions
Problem Statement: Write a Python function to calculate the factorial of a given number.
Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Input: factorial(5) Output: 120
Result: The function calculates the factorial by recursively multiplying numbers from n down
to 1.
2. Classes and Objects
Problem Statement: Create a Student class with attributes name and age. Include a method
to display student details. Code:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Example usage:
student = Student("Alice", 20)
student.display()
Input: Student("Alice", 20).display() Output: Name: Alice, Age: 20
Result: The class stores student information and displays it using the display method.
3. Stack (Using List)
Problem Statement: Implement a stack using Python lists with push and pop operations.
Code:
stack = []
def push(element):
stack.append(element)
print(f"Pushed {element} onto the stack")
def pop():
if not stack:
return "Stack is empty"
return stack.pop()
# Example usage:
push(10)
push(20)
print(pop()) # Output: 20
Input: push(10); push(20); pop() Output: Pushed 10 onto the stack, Pushed 20
onto the stack, 20
Result: Stack operations simulate Last-In-First-Out (LIFO) behavior.
4. Queue (Using List)
Problem Statement: Implement a queue using Python lists with enqueue and dequeue
operations. Code:
queue = []
def enqueue(element):
queue.append(element)
print(f"Enqueued {element} to the queue")
def dequeue():
if not queue:
return "Queue is empty"
return queue.pop(0)
# Example usage:
enqueue(10)
enqueue(20)
print(dequeue()) # Output: 10
Input: enqueue(10); enqueue(20); dequeue()
Output: Enqueued 10 to the queue, Enqueued 20 to the queue, 10
Result: Queue operations simulate First-In-First-Out (FIFO) behavior.
5. Linked List (Singly Linked List)
Problem Statement: Implement a singly linked list with insertion and display methods.
Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def display(self):
current = self.head
while current:
print(current.data, end=" ")
current = current.next
print()
# Example usage:
ll = LinkedList()
ll.insert(10)
ll.insert(20)
ll.display() # Output: 20 10
Input: insert(10); insert(20); display()
Output: 20 10
Result: Each new node is added at the beginning of the list.
6. Recursion (Fibonacci Series)
Problem Statement: Write a recursive function to find the nth Fibonacci number. Code:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example usage:
print(fibonacci(5)) # Output: 5
Input: fibonacci(5)
Output: 5
Result: The function calculates the nth Fibonacci number using recursion.
7. Insertion Sort
Problem Statement: Implement insertion sort to sort a list of numbers in ascending order.
Code:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Example usage:
print(insertion_sort([4, 2, 9, 1]))
Input: [4, 2, 9, 1]
Output: [1, 2, 4, 9]
Result: The array is sorted in ascending order using insertion sort.
8. Bubble Sort
Problem Statement: Implement bubble sort to sort a list of numbers in ascending order.
Code:
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]
return arr
# Example usage:
print(bubble_sort([5, 1, 4, 2]))
Input: [5, 1, 4, 2]
Output: [1, 2, 4, 5]
Result: The array is sorted in ascending order using bubble sort.
9. Binary Search
Problem Statement: Implement binary search to find an element in a sorted list. Code:
def binary_search(arr, x):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
# Example usage:
print(binary_search([1, 2, 4, 5, 7], 5)) # Output: 3
Input: binary_search([1, 2, 4, 5, 7], 5)
Output: 3
Result: Binary search finds the position of the target element in the sorted list.
10. Tree (Binary Tree with Inorder Traversal)
Problem Statement: Create a binary tree and implement inorder traversal. Code:
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root):
if root:
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
# Example usage:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
inorder(root) # Output: 2 1 3
Input: Tree with nodes 1, 2, and 3
Output: 2 1 3
Result: Inorder traversal visits the left subtree, root, and then the right subtree.
11. Graph (Adjacency List Representation)
Problem Statement: Represent a graph using an adjacency list and display it. Code:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def display(self):
for node in self.graph:
print(node, ":", " -> ".join(map(str, self.graph[node])))
# Example usage:
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.display()
Input: Graph edges (0, 1), (0, 2), (1, 2) Output:
0 : 1 -> 2
1 : 2
Result: The graph is represented and displayed using an adjacency list.