Recursion & Lambda Expressions
রিকার্শন ও লাম্বডা — নিজেকে call করা এবং anonymous function
1. What Is Recursion?
Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive solution has two parts: a base case that stops the recursion, and a recursive step that reduces the problem toward that base case.
2. Classic — Factorial
Factorial-এর সংজ্ঞা নিজেই recursive: n! = n × (n-1)! এবং 0! = 1।
def factorial(n):
# base case
if n == 0 or n == 1:
return 1
# recursive step
return n * factorial(n - 1)
for i in range(7):
print(f"{i}! = {factorial(i)}")
3. Fibonacci — এবং Recursion-এর সীমাবদ্ধতা
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
RecursionError আসবে। বিকল্প:
iteration, memoization (functools.lru_cache), বা sys.setrecursionlimit।
Naive Fibonacci O(2ⁿ) — প্রতিটি call দুটি subtree তৈরি করে, অনেক কাজ পুনরাবৃত্তি হয়।
@lru_cache দিলে এটি O(n) হয়ে যায়।
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)) # instant, even at n=50
4. GCD — Euclid's Algorithm
দুই সংখ্যার গরিষ্ঠ সাধারণ গুণনীয়ক বের করার ২০০০+ বছরের পুরোনো elegant recursive algorithm।
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(48, 18)) # 6
print(gcd(100, 75)) # 25
5. Lambda Expressions — Tiny Anonymous Functions
A lambda creates a function in a single expression — useful when you need a throwaway function.
Syntax: lambda parameters: expression. No return needed — the expression's value is returned.
square = lambda x: x * x
print(square(7)) # 49
add = lambda a, b: a + b
print(add(3, 4)) # 7
# lambda inside sorted
students = [("Rafi", 82), ("Mim", 95), ("Sakib", 77)]
top = sorted(students, key=lambda s: s[1], reverse=True)
print(top)
sorted-এর key, map, filter-এ বিশেষভাবে উপযোগী। একাধিক statement-এর দরকার হলে সাধারণ def ব্যবহার করুন।
6. map, filter and sorted(key=)
nums = [1, 2, 3, 4, 5, 6]
# map — apply a function to each element
squares = list(map(lambda x: x * x, nums))
print(squares) # [1, 4, 9, 16, 25, 36]
# filter — keep only elements where predicate is True
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]
# sorted with key — sort strings by length
words = ["python", "is", "awesome", "really"]
print(sorted(words, key=lambda w: len(w)))
7. Vocabulary
| Term | Meaning | বাংলায় |
|---|---|---|
| Recursion | Function that calls itself. | নিজেকে call করে এমন function। |
| Base case | Condition that stops recursion. | যে শর্তে recursion থামে। |
| Call stack | Stack of active function frames. | চলমান function call-এর stack। |
| Memoization | Caching results of function calls. | পূর্বের call-এর ফল cache করা। |
| Lambda | Single-expression anonymous function. | এক-expression-এর anonymous function। |
map(f, xs) | Apply f to every item. | প্রতিটি item-এ f apply করে। |
filter(p, xs) | Keep items where predicate is True. | Predicate সত্য এমন item রাখে। |
8. Practice Problems
-
Write a recursive
power(a, n)that computesa**nfor non-negative integern.Recursivepower(a, n)লিখুন যা non-negative integern-এর জন্যa**nবের করে।✨ Show Answer
ans1.pydef power(a, n): if n == 0: return 1 return a * power(a, n - 1) print(power(2, 10)) # 1024 -
Use
mapand lambda to convert a list of Celsius temperatures to Fahrenheit.mapও lambda ব্যবহার করে Celsius-এর list-কে Fahrenheit-এ রূপান্তর করুন।✨ Show Answer
ans2.pycelsius = [0, 20, 30, 37, 100] fahr = list(map(lambda c: c * 9/5 + 32, celsius)) print(fahr) -
Recursively sum the digits of an integer, e.g.
sum_digits(12345) == 15.Recursive ভাবে একটি integer-এর অঙ্কের যোগফল বের করুন।✨ Show Answer
ans3.pydef sum_digits(n): if n < 10: return n return n % 10 + sum_digits(n // 10) print(sum_digits(12345)) # 15 -
Use
filterto keep only words longer than 4 letters from a list.filterদিয়ে ৪ অক্ষরের বেশি word-গুলো রেখে দিন।✨ Show Answer
ans4.pywords = ["dog", "elephant", "cat", "tiger", "ox"] long_words = list(filter(lambda w: len(w) > 4, words)) print(long_words) -
Explain in 2 lines why Python limits recursion to ~1000 levels.Python কেন recursion ~1000 লেভেলে সীমিত রাখে — ২ লাইনে ব্যাখ্যা করুন।
✨ Show Answer
Each recursive call allocates a new stack frame; the OS-provided thread stack is bounded (typically a few MB). The limit prevents a runaway program from silently exhausting the stack and crashing the interpreter.
প্রতিটি recursive call stack-এ একটি নতুন frame নেয়। OS-এর thread stack সীমিত (সাধারণত কয়েক MB)। এই limit রাখা হয় যাতে ভুল recursion সাইলেন্টলি stack overflow না করে interpreter-কে crash না করে।
Summary — Module 12
Recursion expresses a problem in terms of a smaller version of itself — always with a base case to stop.
Python's default recursion limit is 1000; use iteration or @lru_cache when you need more.
lambda defines tiny anonymous functions, perfect as the key for sorted,
or as the callable passed to map and filter.
@lru_cache ব্যবহার করুন। lambda একটি ছোট anonymous function — বিশেষভাবে sorted, map, filter-এ উপযোগী।