1.3.2 · Coding › Python Intermediate
Python ka slogan hai "batteries included" — standard library ek giant toolbox hai jo Python ke saath hi aata hai, toh wheel ko dobara banane ki zarurat nahi. Mental model yeh hai: har module ek labelled drawer hai pre-tested, C-fast functions ka . Yeh jaanna ki kaun sa drawer kholna hai, 80% productivity hai. Har tool yaad nahi karna; drawers ka map aur har ek mein 3–4 high-value tools yaad karne hain.
Module
Yeh KISLIYE hai (ek word)
Killer tools
math
Pure-number math
sqrt, floor, ceil, gcd, factorial, pi, comb, log
random
Pseudo-randomness
random, randint, choice, shuffle, sample, seed
os
OS / files se baat karna
getcwd, listdir, path.join, environ, makedirs
sys
Interpreter se baat karna
argv, exit, path, maxsize
datetime
Calendar dates & times
datetime.now, timedelta, strftime, strptime
time
Clock / sleep / timing
time(), sleep(), perf_counter()
collections
Better containers
Counter, defaultdict, deque, namedtuple
itertools
Lazy looping algebra
count, cycle, product, permutations, combinations, chain, groupby
functools
Functions par kaam karne wale tools
reduce, lru_cache, partial, wraps
math
Ek module hai C-implemented floating-point aur integer math functions ka, saath mein pi aur e jaisi constants bhi hain. Yeh single numbers par kaam karta hai, arrays par nahi (woh NumPy ka kaam hai).
Worked example Do points ke beech distance
import math
d = math.hypot( 3 , 4 ) # 5.0
hypot kyun? Yeh 3 2 + 4 2 compute karta hai lekin internally scaling karke overflow avoid karta hai — math.sqrt(3**2+4**2) yahan kaam karta hai lekin bade numbers ke liye break ho jaata hai.
Intuition "Seed" kyun matter karta hai
Computer truly random nahi bana sakta; woh ek deterministic formula chalata hai jo random lagta hai. Seed starting point hai. Same seed → same sequence . Yeh ek feature hai: iska matlab random tests reproducible ban jaate hain.
import random
random.seed( 42 )
random.randint( 1 , 6 ) # dice roll, dono ends inclusive
random.choice([ 'a' , 'b' , 'c' ])
random.sample( range ( 10 ), 3 ) # 3 unique items (no repeats)
random.shuffle(my_list) # in-place
randint(1,6) mein 6 kyun include hai? Kyunki yeh human "1 se 6" sochne ke liye design kiya gaya hai — range ke unlike, upper end inclusive hai.
os operating system se baat karta hai: files, directories, environment variables.
sys Python interpreter se khud baat karta hai: command-line args, exit codes, import paths.
Worked example Safe path banao
import os
os.path.join( 'data' , 'raw' , 'file.csv' ) # 'data/raw/file.csv' on Linux, '\\' on Windows
Sirf 'data/' + 'file.csv' kyun nahi? Kyunki separator OS ke hisaab se alag hota hai . os.path.join portable hai — yahi toh poora point hai.
Worked example Command-line arguments
import sys
# run: python script.py hello 7
sys.argv # ['script.py', 'hello', '7']
sys.exit( 0 ) # 0 = success, nonzero = error
argv[0] script ka naam kyun hai? C se inherited convention hai — program "apna naam jaanta hai."
Common mistake Steel-man: "datetime aur time ek hi cheez hain."
Sahi kyun lagta hai: dono "time" se deal karte hain. Fix: time seconds-since-1970 (epoch) aur sleeping/timing se deal karta hai; datetime human calendar objects se deal karta hai (year/month/day ke saath arithmetic). Durations measure karne ke liye time.perf_counter() use karo, date represent karne ke liye datetime use karo.
Worked example Date arithmetic
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta( days = 1 )
now.strftime( '%Y-%m- %d ' ) # format → string
datetime.strptime( '2024-01-31' , '%Y-%m- %d ' ) # parse string → object
timedelta kyun? Date mein 1 add karna ambiguous hai (1 second? day?). timedelta unit ko explicit banata hai. Memory trick: f ormat = s tring mein, p arse = string se (strf vs strp).
Worked example Code ko time karo
import time
t0 = time.perf_counter()
work()
print (time.perf_counter() - t0, "seconds" )
perf_counter kyun, time.time() nahi? perf_counter highest-resolution monotonic clock hai — agar system clock adjust ho jaaye toh yeh kabhi backward nahi jaata.
Counter: ek dict jo automatically occurrences count karta hai .
defaultdict: ek dict jo missing keys ke liye default value create karta hai (koi KeyError nahi).
deque: ek double-ended queue , dono ends par O ( 1 ) append/pop.
namedtuple: ek tuple jisme named fields hote hain (readable, immutable).
Worked example Words count karna
from collections import Counter, defaultdict, deque
Counter( "banana" ) # Counter({'a':3,'n':2,'b':1})
Counter( "banana" ).most_common( 2 ) # [('a',3),('n',2)]
d = defaultdict( list )
d[ 'fruits' ].append( 'apple' ) # key auto-created as []
q = deque([ 1 , 2 , 3 ])
q.appendleft( 0 ); q.pop() # dono sides par fast
Queue ke liye list ki jagah deque kyun? List ke front se remove karna O ( n ) hai (sab kuch shift karna padta hai). deque.popleft() O ( 1 ) hai.
itertools iterators return karta hai, lists nahi. Yeh items ek ek karke, demand par compute karta hai, toh aap count(0) (infinite!) par bhi loop kar sakte ho bina memory fill kiye. ==Lazy = sirf wahi compute karo jo consume karo==.
from itertools import product, permutations, combinations, chain, groupby, count
list (product([ 0 , 1 ], repeat = 2 )) # [(0,0),(0,1),(1,0),(1,1)]
list (permutations( 'ABC' , 2 )) # 6 ordered pairs
list (combinations( 'ABC' , 2 )) # 3 unordered: AB AC BC
list (chain([ 1 , 2 ],[ 3 , 4 ])) # [1,2,3,4] (flatten)
lru_cache se Memoization
from functools import lru_cache, reduce
@lru_cache ( maxsize = None )
def fib (n):
return n if n < 2 else fib(n - 1 ) + fib(n - 2 )
reduce ( lambda a,b: a * b, [ 1 , 2 , 3 , 4 ]) # 24 (factorial-style product)
lru_cache kyun? Naive fib same subproblems exponentially recompute karta hai (O ( 2 n ) ). Cache har result ek baar store karta hai → O ( n ) . LRU = least-recently-used items cache full hone par evict ho jaate hain.
randint(1, n) range jaisa hai — top excluded hai."
Sahi lagta hai kyunki range(1,n) mein n exclude hota hai. Fix: random.randint(a, b) dono ends par inclusive hai. Exclusive top ke liye random.randrange(a, b) use karo.
defaultdict(list) — main list() pass karunga."
Sahi lagta hai (tumhe empty list chahiye). Fix: factory khud list pass karo, list() nahi. defaultdict zarurat padne par factory ko call karta hai. defaultdict([]) error deta hai.
Common mistake "itertools functions lists return karti hain, main unhe index karunga."
Fix: woh one-shot iterators return karti hain. combinations(...)[0] fail hoga; pehle list(...) mein wrap karo, aur yaad rakho ek baar consume hone ke baad woh exhausted ho jaati hain.
Counter, defaultdict, deque ke liye kaun sa module?collections
math.comb(n,k) kya return karta hai, aur kis type mein?( k n ) = k ! ( n − k )! n ! , ek exact integer ke roop mein
Kya random.randint(1,6) mein 6 inclusive hai? Haan — dono endpoints inclusive hain
strftime aur strptime mein kya fark hai?strf = f ormat object→string; strp = p arse string→object
String + ki jagah os.path.join kyun use karo? Yeh correct OS separator use karta hai → portable code
Timing ke liye time.time() ki jagah time.perf_counter() kyun? Highest-resolution monotonic clock; kabhi backward nahi jaata
permutations(n, r) ka size?n ! / ( n − r )!
combinations(n, r) ka size?( r n ) = n ! / ( r ! ( n − r )!)
functools.reduce(f,[a,b,c]) kya compute karta hai?f ( f ( a , b ) , c ) — left-fold accumulation
Recursive fib ke liye lru_cache kya karta hai? Results memoize karta hai → O ( 2 n ) ko O ( n ) mein badal deta hai
defaultdict ko list pass karo, list() kyun nahi?defaultdict khud factory call karta hai jab koi key missing hoti hai
sys.argv[0] kya hai?Script ka apna naam
deque.popleft() list.pop(0) se better kyun hai?O ( 1 ) vs O ( n ) (koi shifting nahi)
Recall Feynman: ek 12-saal ke bacche ko explain karo
Socho ek bada toolbox hai jo tumhari cycle ke saath free mein aata hai. Ek drawer (math) mein number gadgets hain, ek (random) ek dice cup hai, ek (os) tumhare computer se files ke baare mein baat karta hai, ek (collections) mein magic boxes hain jo khud cheezein count karte hain, aur ek (itertools) ek machine hai jo tumhare stickers ke har possible combination banaati hai bina tumhare haath lagaye. Tumhe yeh tools banane nahi hain — woh box mein pehle se hain. Bas tumhe yeh jaanna hai ki kaun sa drawer kholna hai.
"My Real Old Sister Did Try Coding In Functions"
M ath, R andom, O s, S ys, D atetime, T ime, C ollections, I tertools, F unctools.
Python Iterators and Generators — itertools lazy kyun hai
Big-O Notation — deque/lru_cache complexity kyun change karte hain
Recursion and Memoization — lru_cache deep dive
Combinatorics — math.comb, permutations, combinations formulas
File Handling in Python — os aur os.path ke saath pair hota hai
Decorators — functools.wraps, lru_cache, partial
Standard Library batteries included