0% found this document useful (0 votes)
2 views25 pages

100 Advanced Python Programs

This document is a comprehensive reference guide on advanced Python topics, prepared by Siddhu Bankar for a BSc Computer Science course. It covers a wide range of subjects including generators, decorators, OOP concepts, data structures, algorithms, concurrency, and file handling, along with practical code examples. Additionally, it includes a mini project on a Student Report System and various advanced programming techniques.

Uploaded by

pilya9324
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

100 Advanced Python Programs

This document is a comprehensive reference guide on advanced Python topics, prepared by Siddhu Bankar for a BSc Computer Science course. It covers a wide range of subjects including generators, decorators, OOP concepts, data structures, algorithms, concurrency, and file handling, along with practical code examples. Additionally, it includes a mini project on a Student Report System and various advanced programming techniques.

Uploaded by

pilya9324
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

100 Advanced Python

Complete Reference with SourcePrograms


Code

Prepared by: Bankar Siddheshwar Adinath (Siddhu)


S.Y. BSc Computer Science | Arts, Commerce & Science College, Sonai
Savitribai Phule Pune University (SPPU)
Faculty Guide: Prof. T.S. Mehetre

Topics Covered
• Generators, Iterators & Closures
• Decorators, Context Managers, Properties
• OOP – Abstract Classes, Metaclasses, Descriptors, Mixins
• Functional Programming (map, filter, reduce, partial, lru_cache)
• Data Structures – Stack, Queue, Linked List, Binary Tree, Heap
• Algorithms – Binary Search, Bubble/Selection/Merge/Quick Sort, BFS, DFS
• Dynamic Programming – Knapsack, LCS, N-Queens, Tower of Hanoi
• Standard Library – collections, itertools, functools, datetime, re, os
• Concurrency – Threading, Multiprocessing, asyncio, Semaphores
• File I/O – JSON, CSV, Pickle, sqlite3
• Design Patterns – Factory, Observer, Strategy, Command, Chain of Responsibility
• Type System – Typing, Dataclass, Protocol, TypeVar, Enum, __slots__
• Advanced Topics – Walrus operator, match-case, singledispatch, Huffman Encoding
• Mini Project – Student Report System with statistics
1. Fibonacci using Generator
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

gen = fibonacci()
for _ in range(10):
print(next(gen))

2. Decorator – Execution Timer


import time

def timer(func):
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
print(f"Time: {[Link]()-start:.4f}s")
return result
return wrapper

@timer
def slow():
[Link](1)

slow()

3. Context Manager – File Handler


class FileManager:
def __init__(self, name, mode):
[Link] = name
[Link] = mode
def __enter__(self):
[Link] = open([Link], [Link])
return [Link]
def __exit__(self, *args):
[Link]()

with FileManager("[Link]", "w") as f:


[Link]("Hello!")

4. Singleton using Metaclass


class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]

class DB(metaclass=SingletonMeta):
pass

a = DB(); b = DB()
print(a is b) # True

5. Lambda + Map + Filter


nums = [1,2,3,4,5,6,7,8,9,10]
evens = list(filter(lambda x: x%2==0, nums))
squares = list(map(lambda x: x**2, evens))
print(squares) # [4, 16, 36, 64, 100]

6. List Comprehension – Matrix Transpose


matrix = [[1,2,3],[4,5,6],[7,8,9]]
transpose = [[row[i] for row in matrix] for i in range(3)]
print(transpose)

7. *args and **kwargs


def show(*args, **kwargs):
for a in args:
print("arg:", a)
for k, v in [Link]():
print(f"{k} = {v}")

show(1, 2, name="Siddhu", city="Sonai")

8. Abstract Base Class


from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self): pass

class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r**2

print(Circle(5).area())

9. Property Decorator
class Temperature:
def __init__(self, c=0): self._c = c
@property
def fahrenheit(self): return self._c * 9/5 + 32
@[Link]
def fahrenheit(self, f): self._c = (f-32)*5/9

t = Temperature(100)
print([Link]) # 212.0

10. Itertools – Combinations & Permutations


from itertools import combinations, permutations

items = ["A","B","C"]
print(list(combinations(items, 2)))
print(list(permutations(items, 2)))

11. Collections – Counter


from collections import Counter

words = ["apple","banana","apple","cherry","banana","apple"]
c = Counter(words)
print(c.most_common(2)) # [(apple,3),(banana,2)]

12. defaultdict – Graph Adjacency List


from collections import defaultdict

graph = defaultdict(list)
graph["A"].append("B")
graph["A"].append("C")
graph["B"].append("D")
print(dict(graph))

13. Named Tuple


from collections import namedtuple

Student = namedtuple("Student", ["name","roll","marks"])


s = Student("Siddhu", 101, 95)
print([Link], [Link], [Link])

14. Regular Expression – Email Validator


import re

def validate_email(email):
pattern = r"^[\w.-]+@[\w.-]+\.\w{2,}$"
return bool([Link](pattern, email))

print(validate_email("siddhu@[Link]")) # True
print(validate_email("bad@email")) # False

15. Threading
import threading

def print_nums(n):
for i in range(n):
print(f"Thread: {i}")

t = [Link](target=print_nums, args=(5,))
[Link]()
[Link]()
print("Done")

16. Multiprocessing
from multiprocessing import Pool

def square(n): return n * n

if __name__ == "__main__":
with Pool(4) as p:
result = [Link](square, [1,2,3,4,5])
print(result)

17. Async / Await


import asyncio

async def fetch(name, delay):


await [Link](delay)
print(f"{name} done")

async def main():


await [Link](
fetch("Task1", 2),
fetch("Task2", 1)
)

[Link](main())

18. Dataclass
from dataclasses import dataclass, field

@dataclass
class Student:
name: str
roll: int
marks: list = field(default_factory=list)

def average(self):
return sum([Link])/len([Link])

s = Student("Siddhu", 1, [90,85,95])
print([Link]())

19. Enum
from enum import Enum

class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3

for c in Color:
print([Link], [Link])

20. Closure
def multiplier(factor):
def multiply(n): return n * factor
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15

21. Memoization with functools.lru_cache


from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)

print(fib(50))

22. Partial Functions


from functools import partial

def power(base, exp): return base ** exp

square = partial(power, exp=2)


cube = partial(power, exp=3)
print(square(4), cube(3)) # 16 27

23. Operator Overloading


class Vector:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, o): return Vector(self.x+o.x, self.y+o.y)
def __repr__(self): return f"Vector({self.x},{self.y})"

v = Vector(1,2) + Vector(3,4)
print(v) # Vector(4,6)

24. Custom Iterator


class Countdown:
def __init__(self, n): self.n = n
def __iter__(self): return self
def __next__(self):
if self.n <= 0: raise StopIteration
self.n -= 1
return self.n + 1

for x in Countdown(5): print(x)

25. Stack using List


class Stack:
def __init__(self): [Link] = []
def push(self, v): [Link](v)
def pop(self): return [Link]()
def peek(self): return [Link][-1]
def is_empty(self): return len([Link])==0

s = Stack()
[Link](10); [Link](20)
print([Link]()) # 20

26. Queue using deque


from collections import deque

class Queue:
def __init__(self): self.q = deque()
def enqueue(self, v): [Link](v)
def dequeue(self): return [Link]()
def is_empty(self): return len(self.q)==0

q = Queue()
[Link]("A"); [Link]("B")
print([Link]()) # A

27. Singly Linked List


class Node:
def __init__(self, data):
[Link] = data; [Link] = None

class LinkedList:
def __init__(self): [Link] = None
def append(self, data):
node = Node(data)
if not [Link]: [Link] = node; return
cur = [Link]
while [Link]: cur = [Link]
[Link] = node
def display(self):
cur = [Link]
while cur: print([Link], end=" -> "); cur = [Link]
print("None")

ll = LinkedList()
[Link](1); [Link](2); [Link](3)
[Link]()

28. Binary Search


def binary_search(arr, target):
lo, hi = 0, len(arr)-1
while lo <= hi:
mid = (lo+hi)//2
if arr[mid]==target: return mid
elif arr[mid]<target: lo = mid+1
else: hi = mid-1
return -1

print(binary_search([1,3,5,7,9,11], 7)) # 3
29. Merge Sort
def merge_sort(arr):
if len(arr)<=1: return arr
mid = len(arr)//2
L = merge_sort(arr[:mid])
R = merge_sort(arr[mid:])
result = []; i = j = 0
while i<len(L) and j<len(R):
if L[i]<=R[j]: [Link](L[i]); i+=1
else: [Link](R[j]); j+=1
return result + L[i:] + R[j:]

print(merge_sort([5,3,8,1,9,2]))

30. 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)

print(quick_sort([3,6,8,10,1,2,1]))

31. Binary Tree – Inorder Traversal


class Node:
def __init__(self, v): [Link]=v; [Link]=[Link]=None

def inorder(root):
if root:
inorder([Link])
print([Link], end=" ")
inorder([Link])

root = Node(4)
[Link]=Node(2); [Link]=Node(6)
[Link]=Node(1); [Link]=Node(3)
inorder(root) # 1 2 3 4 6

32. Graph – BFS


from collections import deque

def bfs(graph, start):


visited = set([start])
queue = deque([start])
while queue:
node = [Link]()
print(node, end=" ")
for nb in graph[node]:
if nb not in visited:
[Link](nb); [Link](nb)

g = {0:[1,2], 1:[2], 2:[0,3], 3:[3]}


bfs(g, 2)

33. Graph – DFS


def dfs(graph, node, visited=None):
if visited is None: visited = set()
[Link](node)
print(node, end=" ")
for nb in graph[node]:
if nb not in visited:
dfs(graph, nb, visited)

g = {0:[1,2], 1:[0,3], 2:[0], 3:[1]}


dfs(g, 0)

34. Dynamic Programming – 0/1 Knapsack


def knapsack(W, wt, val, n):
dp = [[0]*(W+1) for _ in range(n+1)]
for i in range(1,n+1):
for w in range(W+1):
if wt[i-1]<=w:
dp[i][w]=max(val[i-1]+dp[i-1][w-wt[i-1]], dp[i-1][w])
else:
dp[i][w]=dp[i-1][w]
return dp[n][W]

val=[60,100,120]; wt=[10,20,30]; W=50


print(knapsack(W,wt,val,len(val))) # 220

35. Longest Common Subsequence (DP)


def lcs(X, Y):
m,n = len(X),len(Y)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if X[i-1]==Y[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]

print(lcs("ABCBDAB","BDCAB")) # 4

36. Heap – Priority Queue


import heapq

heap = []
[Link](heap, (3,"low"))
[Link](heap, (1,"high"))
[Link](heap, (2,"medium"))

while heap:
print([Link](heap))

37. File Handling – JSON


import json

data = {"name":"Siddhu","roll":1,"marks":[90,85,95]}

with open("[Link]","w") as f:
[Link](data, f, indent=4)

with open("[Link]","r") as f:
loaded = [Link](f)
print(loaded["name"])

38. CSV Read / Write


import csv

rows = [["Name","Marks"],["Siddhu",95],["Rushikesh",90]]
with open("[Link]","w", newline="") as f:
[Link](f).writerows(rows)

with open("[Link]") as f:
for row in [Link](f): print(row)

39. Custom Exception


class NegativeError(Exception):
def __init__(self, val):
super().__init__(f"Negative not allowed: {val}")

def sqrt(n):
if n < 0: raise NegativeError(n)
return n ** 0.5

try:
print(sqrt(-4))
except NegativeError as e:
print(e)

40. Logging Module


import logging

[Link](
level=[Link],
format="%(asctime)s - %(levelname)s - %(message)s"
)
[Link]("Debug msg")
[Link]("Info msg")
[Link]("Warning!")
[Link]("Error!")

41. Unit Testing with unittest


import unittest

def add(a, b): return a + b

class TestAdd([Link]):
def test_positive(self): [Link](add(2,3), 5)
def test_negative(self): [Link](add(-1,-1), -2)

if __name__ == "__main__": [Link]()

42. Argparse – CLI Calculator


import argparse

parser = [Link](description="Calculator")
parser.add_argument("x", type=float)
parser.add_argument("y", type=float)
parser.add_argument("--op", choices=["+","-","*","/"], default="+")
args = parser.parse_args()

ops={"+":args.x+args.y,"-":args.x-args.y,
"*":args.x*args.y,"/":args.x/args.y}
print(ops[[Link]])

43. pathlib – Directory Walk


from pathlib import Path

def list_py_files(directory):
p = Path(directory)
for f in [Link]("*.py"):
print(f)

list_py_files(".")

44. hashlib – Password Hashing


import hashlib

def hash_password(pw):
return hashlib.sha256([Link]()).hexdigest()

pw = "Secret123"
hashed = hash_password(pw)
print(hashed)
print(hash_password(pw) == hashed) # True

45. sqlite3 – CRUD Operations


import sqlite3

conn = [Link](":memory:")
cur = [Link]()
[Link]("CREATE TABLE students (id INT, name TEXT)")
[Link]("INSERT INTO students VALUES (1, 'Siddhu')")
[Link]()
[Link]("SELECT * FROM students")
print([Link]()) # [(1, "Siddhu")]

46. Typing Module – Type Hints


from typing import List, Dict, Optional, Tuple

def process(students: List[Dict[str,int]]) -> Optional[Tuple[str,int]]:


if not students: return None
top = max(students, key=lambda x: list([Link]())[0])
return list([Link]())[0], list([Link]())[0]

data = [{"Siddhu":95}, {"Rushikesh":90}]


print(process(data)) # ("Siddhu", 95)

47. __slots__ – Memory Optimization


class Point:
__slots__ = ["x","y"]
def __init__(self, x, y): self.x=x; self.y=y
def dist(self): return (self.x**2+self.y**2)**0.5

p = Point(3, 4)
print([Link]()) # 5.0

48. Walrus Operator :=


import re

text = "Python 3.12 released"


if m := [Link](r"Python (\S+)", text):
print("Found:", [Link](1)) # 3.12

nums = [1,2,3,4,5,6]
if (n := len(nums)) > 4:
print(f"Long list: {n}")

49. Pattern Matching (match-case)


def http_status(code):
match code:
case 200: return "OK"
case 404: return "Not Found"
case 500: return "Server Error"
case _: return "Unknown"

print(http_status(404))
print(http_status(200))

50. Zip and Unzip


names = ["Siddhu","Rushikesh","Priya"]
marks = [95, 90, 88]
cities = ["Sonai","Pune","Mumbai"]

combined = list(zip(names, marks, cities))


print(combined)

n, m, c = zip(*combined)
print(list(n))

51. Dictionary Comprehension


students = {"Siddhu":95,"Rushikesh":90,"Priya":88}
toppers = {k:v for k,v in [Link]() if v>=90}
print(toppers)

squares = {x: x**2 for x in range(1,6)}


print(squares)

52. Set Operations


A = {1,2,3,4,5}
B = {3,4,5,6,7}

print(A | B) # Union
print(A & B) # Intersection
print(A - B) # Difference
print(A ^ B) # Symmetric Difference

53. heapq – N Largest / Smallest


import heapq

nums = [3,1,4,1,5,9,2,6,5,3,5]
print([Link](3, nums)) # [9,6,5]
print([Link](3, nums)) # [1,1,2]

54. Bisect – Sorted List Insert


import bisect

sorted_list = [1,3,5,7,9]
[Link](sorted_list, 4)
print(sorted_list) # [1,3,4,5,7,9]
pos = bisect.bisect_left(sorted_list, 5)
print(pos) # 3

55. ChainMap
from collections import ChainMap

defaults = {"theme":"dark","lang":"en"}
user = {"lang":"mr","font":"large"}

combined = ChainMap(user, defaults)


print(combined["theme"]) # dark
print(combined["lang"]) # mr (user overrides)

56. Struct – Binary Packing


import struct

packed = [Link]("iif", 10, 20, 3.14)


print("Packed:", packed)
unpacked = [Link]("iif", packed)
print("Unpacked:", unpacked)

57. Calendar Module


import calendar

print([Link](2024, 8))
print("Leap 2024:", [Link](2024))
print("Weekday of Jan 1 2024:", [Link](2024,1,1))

58. Datetime Operations


from datetime import datetime, timedelta

now = [Link]()
print("Now:", [Link]("%d-%m-%Y %H:%M"))
future = now + timedelta(days=30)
print("30 days later:", [Link]())
print("Days diff:", (future-now).days)

59. Random Module


import random

print([Link](1, 100))
print([Link](["a","b","c"]))

items = [1,2,3,4,5]
[Link](items)
print(items)
print([Link](range(100), 5))

60. sys Module


import sys

print("Python:", [Link])
print("Platform:", [Link])
print("Max int:", [Link])
print("Recursion limit:", [Link]())

61. Inspect Module


import inspect

def greet(name: str, greeting: str = "Hello") -> str:


return f"{greeting}, {name}!"

print([Link](greet))
for name, param in [Link](greet).[Link]():
print(name, "default:", [Link])

62. Pickle – Object Serialization


import pickle

data = {"name":"Siddhu","marks":[90,85,95]}

with open("[Link]","wb") as f: [Link](data, f)


with open("[Link]","rb") as f: loaded = [Link](f)
print(loaded)
63. Copy – Shallow vs Deep
import copy

original = [[1,2],[3,4]]
shallow = [Link](original)
deep = [Link](original)

original[0][0] = 99
print("Shallow:", shallow) # Affected
print("Deep:", deep) # Not affected

64. __repr__ and __str__


class Product:
def __init__(self, name, price): [Link]=name; [Link]=price
def __str__(self): return f"{[Link]} - Rs.{[Link]}"
def __repr__(self): return f"Product({[Link]!r},{[Link]})"

p = Product("Pen", 10)
print(str(p))
print(repr(p))

65. Chained Comparisons


x = 15
print(10 < x < 20) # True
print(1 < 2 < 3 < 4) # True

def valid_marks(m): return 0 <= m <= 100


print(valid_marks(95)) # True
print(valid_marks(-5)) # False

66. String Methods – Advanced


s = " Hello, World! "
print([Link]())
print([Link]())
print([Link]("World","Python"))
print("-".join(["a","b","c"]))
print("Python".center(20,"*"))
print("abc".zfill(8))

67. Enumerate with Start


fruits = ["apple","banana","cherry"]
for i, f in enumerate(fruits, start=1):
print(f"{i}. {f}")

students = ["Siddhu","Rushikesh","Priya"]
roll_dict = {i:s for i,s in enumerate(students,101)}
print(roll_dict)

68. Sorted with Key Function


students = [
{"name":"Siddhu", "marks":95},
{"name":"Rushikesh", "marks":90},
{"name":"Priya", "marks":88}
]

by_marks = sorted(students, key=lambda x: x["marks"], reverse=True)


for s in by_marks: print(s["name"],"-",s["marks"])

69. all() and any()


marks = [85, 90, 78, 95, 88]
print(all(m >= 60 for m in marks)) # All pass
print(any(m >= 90 for m in marks)) # Some distinction
print(all(m >= 90 for m in marks)) # All distinction?

flags = [True, True, False]


print(any(flags)) # True
print(all(flags)) # False

70. zip_longest
from itertools import zip_longest

names = ["Siddhu","Rushikesh","Priya"]
marks1 = [95, 90]
marks2 = [85]

for row in zip_longest(names, marks1, marks2, fillvalue="-"):


print(row)

71. accumulate – Running Totals


from itertools import accumulate
import operator

nums = [1,2,3,4,5]
print(list(accumulate(nums))) # Running sum
print(list(accumulate(nums, [Link]))) # Running product
print(list(accumulate(nums, max))) # Running max

72. Cartesian Product


from itertools import product

colors = ["R","G","B"]
sizes = ["S","M","L"]

for combo in product(colors, sizes):


print(combo, end=" ")
print()
print(list(product(range(2), repeat=3)))

73. groupby – Group Students by Grade


from itertools import groupby
students = [("A","Siddhu"),("B","Ram"),("A","Priya"),("B","Asha")]
[Link](key=lambda x: x[0])
for grade, group in groupby(students, key=lambda x: x[0]):
names = [s[1] for s in group]
print(grade, ":", names)

74. tee – Duplicate Iterators


from itertools import tee

def gen():
for i in range(5): yield i

g1, g2 = tee(gen())
print(list(g1)) # [0,1,2,3,4]
print(list(g2)) # [0,1,2,3,4]

75. contextlib – suppress


from contextlib import suppress
import os

with suppress(FileNotFoundError):
[Link]("nonexistent_file.txt")

with suppress(ZeroDivisionError):
result = 1/0

print("Continued without crash")

76. contextlib – redirect_stdout


from contextlib import redirect_stdout
import io

buffer = [Link]()
with redirect_stdout(buffer):
print("Captured output")
print("Line 2")

print("Got:", repr([Link]()))

77. Dataclass – post_init & ClassVar


from dataclasses import dataclass, field
from typing import ClassVar

@dataclass
class Circle:
radius: float
PI: ClassVar[float] = 3.14159
area: float = field(init=False)

def __post_init__(self):
[Link] = [Link] * [Link]**2

c = Circle(5)
print([Link]) # 78.53975

78. Protocol – Structural Subtyping


from typing import Protocol

class Drawable(Protocol):
def draw(self) -> None: ...

class Circle:
def draw(self): print("Drawing Circle")

class Square:
def draw(self): print("Drawing Square")

def render(shape: Drawable): [Link]()

render(Circle())
render(Square())

79. TypeVar and Generic Class


from typing import TypeVar, Generic

T = TypeVar("T")

class Box(Generic[T]):
def __init__(self, val: T): [Link] = val
def get(self) -> T: return [Link]

int_box = Box(42)
str_box = Box("hello")
print(int_box.get())
print(str_box.get())

80. Async Generator


import asyncio

async def async_range(n):


for i in range(n):
await [Link](0.1)
yield i

async def main():


async for val in async_range(5):
print(val)

[Link](main())

81. Semaphore – Rate Limiting


import asyncio

sem = [Link](2) # Max 2 concurrent

async def task(name):


async with sem:
print(f"{name} started")
await [Link](1)
print(f"{name} done")

async def main():


await [Link](*[task(f"T{i}") for i in range(5)])

[Link](main())

82. Subprocess
import subprocess

result = [Link](
["python","--version"],
capture_output=True, text=True
)
print([Link])
print("Return code:", [Link])

83. Mixin Classes


class LogMixin:
def log(self, msg):
print(f"[LOG] {self.__class__.__name__}: {msg}")

class SerializeMixin:
def serialize(self): return str(self.__dict__)

class User(LogMixin, SerializeMixin):


def __init__(self, name): [Link] = name

u = User("Siddhu")
[Link]("Created")
print([Link]())

84. Descriptor Protocol


class PositiveNumber:
def __set_name__(self, owner, name): [Link] = name
def __get__(self, obj, typ): return obj.__dict__.get([Link])
def __set__(self, obj, val):
if val < 0: raise ValueError("Must be positive")
obj.__dict__[[Link]] = val

class Rectangle:
width = PositiveNumber()
height = PositiveNumber()
def __init__(self,w,h): [Link]=w; [Link]=h
def area(self): return [Link]*[Link]

print(Rectangle(4,5).area())

85. __getattr__ and __setattr__


class DynamicClass:
def __init__(self): self._data = {}

def __setattr__(self, name, val):


if [Link]("_"): super().__setattr__(name, val)
else: self._data[name] = val

def __getattr__(self, name):


if name in self._data: return self._data[name]
raise AttributeError(name)

d = DynamicClass()
[Link] = "Siddhu"; [Link] = 20
print([Link], [Link])

86. singledispatch – Function Overloading


from functools import singledispatch

@singledispatch
def process(val): print(f"Generic: {val}")

@[Link](int)
def _(val): print(f"Int: {val*2}")

@[Link](str)
def _(val): print(f"Str: {[Link]()}")

@[Link](list)
def _(val): print(f"List len: {len(val)}")

process(10)
process("hello")
process([1,2,3])

87. Coroutine Pipeline


def producer(pipeline):
next(pipeline)
for i in range(5): [Link](i*i)
[Link]()

def consumer():
result = []
try:
while True: [Link]((yield))
except GeneratorExit:
print("Result:", result)

producer(consumer())

88. Abstract Factory Pattern


from abc import ABC, abstractmethod

class Button(ABC):
@abstractmethod
def render(self): pass
class WindowsButton(Button): def render(self): print("Windows Button")
class MacButton(Button): def render(self): print("Mac Button")

class GUIFactory(ABC):
@abstractmethod
def create_button(self): pass

class WinFactory(GUIFactory): def create_button(self): return WindowsButton()


class MacFactory(GUIFactory): def create_button(self): return MacButton()

for F in [WinFactory, MacFactory]:


F().create_button().render()

89. Observer Pattern


class EventEmitter:
def __init__(self): self._listeners = {}
def on(self, event, fn):
self._listeners.setdefault(event,[]).append(fn)
def emit(self, event, *args):
for fn in self._listeners.get(event,[]): fn(*args)

ee = EventEmitter()
[Link]("data", lambda x: print("Handler1:", x))
[Link]("data", lambda x: print("Handler2:", x*2))
[Link]("data", 42)

90. Strategy Pattern


from typing import Callable

class Sorter:
def __init__(self, strategy: Callable):
[Link] = strategy
def sort(self, data): return [Link](data)

ascending = lambda d: sorted(d)


descending = lambda d: sorted(d, reverse=True)

data = [3,1,4,1,5,9]
print(Sorter(ascending).sort(data))
print(Sorter(descending).sort(data))

91. Chain of Responsibility


class Handler:
def __init__(self, successor=None): [Link] = successor
def handle(self, r):
if [Link]: return [Link](r)

class LowHandler(Handler):
def handle(self, r):
if r < 10: print(f"Low handles {r}")
else: super().handle(r)

class HighHandler(Handler):
def handle(self, r): print(f"High handles {r}")

chain = LowHandler(HighHandler())
[Link](5)
[Link](50)

92. Command Pattern


class Light:
def on(self): print("Light ON")
def off(self): print("Light OFF")

class TurnOn:
def __init__(self, l): self.l = l
def execute(self): [Link]()

class TurnOff:
def __init__(self, l): self.l = l
def execute(self): [Link]()

class Remote:
def __init__(self): [Link] = []
def press(self, cmd): [Link](); [Link](cmd)

light = Light(); remote = Remote()


[Link](TurnOn(light))
[Link](TurnOff(light))

93. Bubble Sort


def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped: break
return arr

print(bubble_sort([64,34,25,12,22,11,90]))

94. Selection Sort


def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]: min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr

print(selection_sort([64,25,12,22,11]))

95. Tower of Hanoi


def hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1: {source} -> {target}")
return
hanoi(n-1, source, auxiliary, target)
print(f"Move disk {n}: {source} -> {target}")
hanoi(n-1, auxiliary, target, source)

hanoi(3, "A", "C", "B")

96. Caesar Cipher


def caesar_encrypt(text, shift):
result = ""
for ch in text:
if [Link]():
base = ord("A") if [Link]() else ord("a")
result += chr((ord(ch)-base+shift)%26+base)
else: result += ch
return result

msg = "Hello Siddhu"


enc = caesar_encrypt(msg, 3)
dec = caesar_encrypt(enc, -3)
print(enc)
print(dec)

97. Matrix Multiplication


def mat_mul(A, B):
rows_A, cols_A = len(A), len(A[0])
cols_B = len(B[0])
C = [[0]*cols_B for _ in range(rows_A)]
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
C[i][j] += A[i][k]*B[k][j]
return C

A = [[1,2],[3,4]]; B = [[5,6],[7,8]]
for row in mat_mul(A,B): print(row)

98. N-Queens Problem


def solve_nqueens(n):
def is_safe(board, row, col):
for i in range(row):
if (board[i]==col or
board[i]-i==col-row or
board[i]+i==col+row): return False
return True
def solve(board, row):
if row==n: [Link](board[:]); return
for col in range(n):
if is_safe(board,row,col):
board[row]=col
solve(board,row+1)
board[row]=-1
solutions=[]; solve([-1]*n, 0)
return len(solutions)

print(f"4-queens: {solve_nqueens(4)} solutions")


print(f"8-queens: {solve_nqueens(8)} solutions")

99. Huffman Encoding


import heapq
from collections import Counter

def huffman(text):
freq = Counter(text)
heap = [[wt,[sym,""]] for sym,wt in [Link]()]
[Link](heap)
while len(heap) > 1:
lo = [Link](heap)
hi = [Link](heap)
for pair in lo[1:]: pair[1] = "0"+pair[1]
for pair in hi[1:]: pair[1] = "1"+pair[1]
[Link](heap, [lo[0]+hi[0]] + lo[1:] + hi[1:])
return {sym:code for sym,code in sorted([Link](heap)[1:])}

codes = huffman("hello world")


for ch, code in [Link]():
print(f"{ch!r}: {code}")

100. Full Mini Project – Student Report System


from dataclasses import dataclass, field
from statistics import mean, stdev
from typing import List

@dataclass
class Student:
name: str
roll: int
marks: List[float] = field(default_factory=list)
subjects: List[str] = field(default_factory=list)

@property
def total(self): return sum([Link])
@property
def average(self): return mean([Link])
@property
def grade(self):
a = [Link]
if a>=90: return "O"
if a>=75: return "A"
if a>=60: return "B"
if a>=50: return "C"
return "F"

def report(self):
print(f"\n=== {[Link]} (Roll {[Link]}) ===")
for sub,m in zip([Link],[Link]):
print(f" {sub:<20}: {m:.1f}")
print(f" Total : {[Link]}")
print(f" Average: {[Link]:.2f}")
print(f" Grade : {[Link]}")

def class_stats(students):
avgs = [[Link] for s in students]
print(f"\nClass Avg: {mean(avgs):.2f}")
print(f"Std Dev : {stdev(avgs):.2f}")
top = max(students, key=lambda s: [Link])
print(f"Topper : {[Link]} ({[Link]:.2f})")

subjects = ["Python","DBMS","OS","CN","Maths"]
s1=Student("Siddhu", 1,[95,90,88,92,96],subjects)
s2=Student("Rushikesh",2,[85,80,88,79,91],subjects)
s3=Student("Priya", 3,[78,82,75,80,85],subjects)

for s in [s1,s2,s3]: [Link]()


class_stats([s1,s2,s3])

You might also like