Binary Search (Recursive) (1)
Binary Search (Recursive) (1)
• A perfect number is a number that is equal to the sum of its positive divisors
(excluding itself). Write a program to check if a number is perfect.
def check_perfect_number(num):
if sum(divisors) == num:
else:
check_perfect_number(6)
1. Compute GCD
• Implement the Euclidean algorithm to find the GCD (Greatest Common Divisor)
of two numbers using a while loop.
while b:
a, b = b, a % b
return a
print(compute_gcd(56, 98))
1. Compute LCM
• Write a Python function to compute the LCM (Least Common Multiple) of two
numbers, leveraging the GCD.
print(compute_lcm(12, 15))
1. Count Words
• Write a program to count the number of words in a user-input string (words are
separated by spaces).
def count_words(string):
words = string.split()
def check_armstrong_number(num):
if sum_of_powers == num:
else:
1. Sum of Series
• Write a Python program to calculate the sum of the series 1 + 1/2 + 1/3 + … + 1/n
using a for loop.
def sum_of_series(n):
sum_of_series(5)
• Write a program that generates all prime numbers in a given range [start, end].
primes = []
if num > 1:
if num % i == 0:
break
else:
primes.append(num)
1. Collatz Sequence
• Write a program that displays the Collatz sequence for any positive integer
given by the user.
def collatz_sequence(n):
while n != 1:
if n % 2 == 0:
n //= 2
else:
n=3*n+1
print(n)
collatz_sequence(7)
1. Diamond Pattern
• Print a diamond-shaped pattern of stars with a width given by the user (e.g.,
for 5).
def diamond_pattern(width):
1. FizzBuzz
• Print the numbers from 1 to n. For multiples of 3, print “Fizz” instead of the
number; for multiples of 5, print “Buzz”; for multiples of both 3 and 5, print
“FizzBuzz”.
def fizz_buzz(n):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizz_buzz(15)
count = string.count(char)
print(f"The character '{char}' appears {count} times.")
1. List of Squares
print(squares)
1. Sum of List
def sum_of_list(lst):
return sum(lst)
my_list = [1, 2, 3, 4, 5]
print(sum_of_list(my_list))
• Write a function that returns the largest and the smallest elements in a given
list.
def find_largest_smallest(lst):
1. Remove Duplicates
• Write a Python function that removes duplicate elements from a list and
returns the new list.
def remove_duplicates(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(my_list))
1. Linear Search
• Implement a linear search to find a given element in a list. Return the index if
found, or -1 otherwise.
if element == target:
return index
return -1
my_list = [3, 6, 2, 9, 5]
print(linear_search(my_list, 9))
print(linear_search(my_list, 7))
1. Bubble Sort
• Implement the bubble sort algorithm to sort a list in ascending order.
def bubble_sort(lst):
n = len(lst)
for i in range(n):
return lst
my_list = [5, 3, 8, 6, 2]
print(bubble_sort(my_list))
1. List Reversal
def list_reversal(lst):
my_list = [1, 2, 3, 4, 5]
list_reversal(my_list)
print(my_list)
• Write a Python program that counts the number of times a given element
appears in a list.
def count_occurrences(lst, element):
return lst.count(element)
my_list = [1, 2, 3, 1, 1, 4]
print(count_occurrences(my_list, 1))
1. Rotate List
k = k % len(lst)
my_list = [1, 2, 3, 4, 5]
print(rotate_list(my_list, 2))
1. Second Largest
def second_largest(lst):
lst = list(set(lst))
lst.sort()
my_list = [5, 3, 8, 6, 2]
print(second_largest(my_list))
1. Merge Two Sorted Lists
• Write a function that merges two sorted lists into one sorted list.
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(merge_sorted_lists(list1, list2))
1. Find Duplicates
def find_duplicates(lst):
duplicates = []
seen = set()
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return duplicates
my_list = [1, 2, 2, 3, 4, 4, 5]
print(find_duplicates(my_list))
1. Remove Even Numbers
def remove_even_numbers(lst):
my_list = [1, 2, 3, 4, 5, 6]
print(remove_even_numbers(my_list))
1. In-Place Shuffle
import random
def in_place_shuffle(lst):
random.shuffle(lst)
return lst
my_list = [1, 2, 3, 4, 5]
print(in_place_shuffle(my_list))
1. Check Sorted
def check_sorted(lst):
print(check_sorted(my_list))
• Given two lists of the same length, create a dictionary mapping elements of
one list to the corresponding elements of the other.
values = [1, 2, 3]
print(dict_from_two_lists(keys, values))
1. Frequency Count
• Write a program that counts the frequency of each element in a list using a
dictionary.
def frequency_count(lst):
freq = {}
freq[item] = freq.get(item, 0) + 1
return freq
my_list = [1, 2, 2, 3, 3, 3, 4]
print(frequency_count(my_list))
1. Invert Dictionary
• Write a function that inverts a dictionary (keys become values, values become
keys).
def invert_dictionary(d):
print(invert_dictionary(my_dict))
return key in d
print(check_key_existence(my_dict, 'b'))
print(check_key_existence(my_dict, 'd'))
1. Dictionary Merge
• Write a function to merge two dictionaries. If a key appears in both, add their
values.
merged = d1.copy()
for key, value in d2.items():
return merged
print(dictionary_merge(dict1, dict2))
def sort_dict_by_value(d):
print(sort_dict_by_value(my_dict))
1. Generate Dictionary
def generate_dict(n):
print(generate_dict(5))
1. Set Operations
• Write a Python program to perform union, intersection, and difference
operations on two sets.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set_operations(set1, set2))
• Given a list with duplicates, use a set to create a list of unique elements (in any
order).
def unique_elements(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 4, 4, 5]
print(unique_elements(my_list))
1. Common Elements
• Given two lists, write a program to find the common elements using sets.
list2 = [3, 4, 5, 6]
print(common_elements(list1, list2))
1. Recursive Factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print(factorial(5))
1. Recursive Fibonacci
def fib(n):
if n <= 1:
return n
print(fib(5))
1. Power Function
if exp == 0:
return 1
print(power(2, 3))
• Write a recursive function that computes the sum of all elements in a list.
def sum_of_list(lst):
if not lst:
return 0
my_list = [1, 2, 3, 4, 5]
print(sum_of_list(my_list))
return -1
if arr[mid] == target:
return mid
else:
if __name__ == "__main__":
target = 11
if result != -1:
else:
1. Hanoi Towers
if n > 0:
def count_vowels(s):
• Write a recursive function that takes a list which may contain nested lists and returns a flat
list of all elements.
def flatten_list(nested_list):
if not nested_list:
return []
if isinstance(nested_list[0], list):
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("lol"))
1. GCD (Recursive)
• Write a recursive function to compute the Greatest Common Divisor (GCD) of two numbers.
if b == 0:
return a
return gcd(b, a % b)
print(gcd(56, 98))
1. Read File
• Write a Python script that reads a text file and prints its contents.
def read_file(file_name):
try:
content = file.read()
print(content)
except FileNotFoundError:
print(f"File {file_name} not found.")
except Exception as e:
read_file('example.txt')
1. Write File
• Write a program that prompts the user for a line of text and writes that line to a file.
def write_to_file(file_name):
file.write(text)
write_to_file('output.txt')
1. Copy File
try:
content = src.read()
dest.write(content)
except FileNotFoundError:
copy_file('source.txt', 'destination.txt')
• Write a Python program that reads a file and counts the number of words in it.
def word_count_in_file(file_name):
try:
content = file.read()
words = content.split()
except FileNotFoundError:
except Exception as e:
word_count_in_file('example.txt')
1. Line Count
def line_count_in_file(file_name):
try:
lines = file.readlines()
print(f"Number of lines in {file_name}: {len(lines)}")
except FileNotFoundError:
except Exception as e:
line_count_in_file('example.txt')
• Modify the file-reading program to handle exceptions (e.g., file not found) gracefully.
def read_file_with_exception_handling(file_name):
try:
content = file.read()
print(content)
except FileNotFoundError:
except PermissionError:
except Exception as e:
read_file_with_exception_handling('example.txt')
• Write a program that finds the longest word in a text file and prints it.
def find_longest_word(file_name):
try:
content = file.read()
words = content.split()
except FileNotFoundError:
except Exception as e:
find_longest_word('example.txt')
1. Search in File
• Write a program to search for a specific substring in a file and print the lines where it
appears.
try:
lines = file.readlines()
found = False
if substring in line:
found = True
if not found:
except FileNotFoundError:
except Exception as e:
search_in_file('example.txt', 'search_term')
1. Append to File
• Write a program that appends a user-input line to an existing file without overwriting it.
def append_to_file(file_name):
file.write(text + '\n')
append_to_file('example.txt')
1. CSV Reader
• Write a Python script to read a CSV file and print each row.
import csv
def read_csv(file_name):
try:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
except FileNotFoundError:
except Exception as e:
read_csv('example.csv')
7. Object-Oriented Programming
1. Simple Class
• Define a class Person with attributes name and age. Create an instance of this class and
print its attributes.
class Person:
self.name = name
self.age = age
print(person.name, person.age)
1. Method in Class
• Add a method greet to the Person class that prints "Hello, my name is <name>".
class Person:
self.name = name
self.age = age
def greet(self):
person.greet()
1. Constructor
• Define a class Car with a constructor that sets make, model, and year. Create an instance
and display its details.
class Car:
self.make = make
self.model = model
self.year = year
def display_details(self):
car.display_details()
• Modify the Car class to have default values for make and model if not provided.
class Car:
def __init__(self, make='Ford', model='Focus', year=2022):
self.make = make
self.model = model
self.year = year
def display_details(self):
car = Car()
car.display_details()
1. Inheritance
• Create a base class Animal and a derived class Dog. The Dog class should inherit attributes
and methods from Animal.
class Animal:
self.species = species
def speak(self):
class Dog(Animal):
super().__init__('Dog')
self.name = name
self.breed = breed
def bark(self):
dog.speak()
dog.bark()
1. Method Overriding
• In the Dog class, override a method speak defined in Animal (e.g., Animal says “Some sound”,
but Dog says “Woof!”).
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak()
1. Multiple Classes
• Create classes Rectangle and Square. Square should inherit from Rectangle (or implement
composition) in a way that automatically sets the length and width to the same value.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
class Square(Rectangle):
super().__init__(side, side)
square = Square(5)
1. Encapsulation
• Demonstrate encapsulation by creating a class with private attributes and use getter and
setter methods to access/modify them.
class Person:
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
self.__age = age
print(person.get_name())
person.set_name("Bob")
print(person.get_name())
1. Polymorphism
class Circle:
def draw(self):
print("Drawing a circle")
class Triangle:
def draw(self):
print("Drawing a triangle")
class Square:
def draw(self):
print("Drawing a square")
shape.draw()
• Create a class Counter with a class variable count. Implement a @classmethod to increment
count and a @staticmethod to display some utility message.
class Counter:
count = 0
@classmethod
def increment(cls):
cls.count += 1
@staticmethod
def utility_message():
Counter.increment()
print(Counter.count)
Counter.utility_message()
1. Magic Methods
• Implement a Python class that overloads the str method to return a string representation of
the object.
class Person:
self.name = name
self.age = age
def __str__(self):
print(person)
1. Operator Overloading
• Create a class Point that overloads the + operator (using add) to add the coordinates of two
Point objects.
class Point:
self.x = x
self.y = y
p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2
print(result.x, result.y)
1. Abstract Class
• Use the abc module to define an abstract base class Shape with an abstract method area().
Implement subclasses Circle and Rectangle.
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
self.radius = radius
def area(self):
class Rectangle(Shape):
self.width = width
self.height = height
def area(self):
return self.width * self.height
1. Property Decorator
• Create a class that uses the @property decorator to get/set an attribute with some
validation logic.
class Temperature:
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
self._celsius = value
temp = Temperature(25)
print(temp.celsius)
temp.celsius = 30
print(temp.celsius)
1. Multiple Inheritance
Demonstrate multiple inheritance with two parent classes providing different
functionalities to a child class.
class Father:
def speak(self):
print("Father speaking")
class Mother:
def sing(self):
print("Mother singing")
pass
child = Child()
child.speak()
child.sing()
import math
def math_operations():
print(f"Floor: {math.floor(num)}")
print(f"Ceiling: {math.ceil(num)}")
math_operations()
import random
def random_element():
items = [1, 2, 3, 4, 5]
random_element()
import datetime
def current_datetime():
now = datetime.datetime.now()
current_datetime()
1. Python OS Module
Write a program that lists all files and directories in the current directory using os.listdir().
import os
def list_files():
files = os.listdir()
print(file)
list_files()
1. Statistics Module
Use the statistics module to compute the mean, median, and mode of a list of number
import statistics
def stats_operations():
numbers = [1, 2, 2, 3, 4, 5, 6]
print(f"Mean: {statistics.mean(numbers)}")
print(f"Median: {statistics.median(numbers)}")
print(f"Mode: {statistics.mode(numbers)}")
stats_operations()
1. Sys Module
Write a script that takes command-line arguments and prints them.
import sys
def print_arguments():
1. Json Module
Write a script that reads a JSON file, modifies a value, and writes the updated data back
to the file.
import json
def modify_json():
data = json.load(file)
data['key'] = 'new_value'
modify_json()
1. Requests Module
Write a program (assuming you have internet access) that fetches data from a public API
using the requests module and prints part of the JSON response.
import requests
def fetch_api_data():
url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(url)
data = response.json()
print(f"Title: {data['title']}")
fetch_api_data()
1. Regex Basics
Write a script that extracts all email addresses from a given string using the re module.
import re
def extract_emails():
extract_emails()
1. Logging
Write a script that uses the logging module to log debug, info, warning, and error
messages to a file.
import logging
def setup_logging():
logging.basicConfig(filename='app.log', level=logging.DEBUG)
setup_logging()
9. Advanced Topics
1. List Slicing
Demonstrate advanced list slicing (e.g., reversing a list with slicing, skipping elements) in
a script.
def list_slicing():
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list_slicing()
def lambda_map():
numbers = [1, 2, 3, 4, 5]
lambda_map()
numbers = [1, 2, 3, 4, 5, 6]
filter_reduce()
def list_vs_generator():
print("List:", large_list[:5])
print("Generator:", list(large_gen)[:5])
list_vs_generator()
1. Decorators
Write a simple decorator timer that measures the execution time of a function.
import time
def timer_decorator(func):
def wrapper():
start_time = time.time()
func()
end_time = time.time()
return wrapper
@timer_decorator
def example_function():
time.sleep(2)
example_function()
1. Context Manager
Implement a context manager using the with statement that opens a file, writes text, and
closes the file automatically.
class FileManager:
def __enter__(self):
return self.file
self.file.close()
with FileManager() as f:
f.write("Hello, world!")
1. Threading
Write a Python program that spawns two threads: one prints numbers 1 to 5, the other
prints letters A to E.
import threading
def print_numbers():
print(i)
def print_letters():
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
1. Multiprocessing
Use the multiprocessing module to run a function in parallel processes and aggregate the
results.
import multiprocessing
def worker(number):
return number * 2
def run_in_parallel():
print("Results:", results)
run_in_parallel()
1. Asyncio Basics
Write a simple asynchronous function using asyncio that prints a message, waits 1
second, and prints another message.
import asyncio
print("Message 1")
await asyncio.sleep(1)
print("Message 2")
asyncio.run(print_messages())
def get_valid_number():
while True:
try:
break
except ValueError:
get_valid_number()