Recursion & Lambda Expressions

রিকার্শন ও লাম্বডা — নিজেকে call করা এবং anonymous function

Read: ~30 min Intermediate 5 practice problems Live code runner

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.

Recursion মানে একটি function নিজেকে call করে — একই সমস্যার একটি ছোট সংস্করণের উপর। প্রতিটি recursive solution-এর দুটি অংশ থাকে: একটি base case (যেখানে recursion থামে), এবং একটি recursive step (যা সমস্যাটিকে base case-এর দিকে নিয়ে যায়)।

2. Classic — Factorial

Factorial-এর সংজ্ঞা নিজেই recursive: n! = n × (n-1)! এবং 0! = 1।

factorial.py
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)}")
factorial(4) 4 × factorial(3) 3 × factorial(2) 2 × factorial(1) = 1 Figure 12.1 — factorial(4)-এর recursive call chain।
প্রতিটি call stack-এ একটি নতুন frame তৈরি করে। Base case-এ পৌঁছালে সেই frame return করে, আগের frame তার মান ব্যবহার করে নিজের হিসাব শেষ করে।

3. Fibonacci — এবং Recursion-এর সীমাবদ্ধতা

fib.py
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]
⚠️ Python-এর recursion limit 1000। বড় input-এ RecursionError আসবে। বিকল্প: iteration, memoization (functools.lru_cache), বা sys.setrecursionlimit।

Naive Fibonacci O(2ⁿ) — প্রতিটি call দুটি subtree তৈরি করে, অনেক কাজ পুনরাবৃত্তি হয়। @lru_cache দিলে এটি O(n) হয়ে যায়।
fib_cached.py
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।

gcd.py
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.

lambda_basics.py
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)
Lambda হলো একটি ছোট function যা একটি expression-এই থাকে। এটি sorted-এর key, map, filter-এ বিশেষভাবে উপযোগী। একাধিক statement-এর দরকার হলে সাধারণ def ব্যবহার করুন।

6. map, filter and sorted(key=)

functional.py
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

TermMeaningবাংলায়
RecursionFunction that calls itself.নিজেকে call করে এমন function।
Base caseCondition that stops recursion.যে শর্তে recursion থামে।
Call stackStack of active function frames.চলমান function call-এর stack।
MemoizationCaching results of function calls.পূর্বের call-এর ফল cache করা।
LambdaSingle-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

  1. Write a recursive power(a, n) that computes a**n for non-negative integer n.
    Recursive power(a, n) লিখুন যা non-negative integer n-এর জন্য a**n বের করে।
    ✨ Show Answer
    ans1.py
    def power(a, n):
        if n == 0:
            return 1
        return a * power(a, n - 1)
    
    print(power(2, 10))   # 1024
  2. Use map and lambda to convert a list of Celsius temperatures to Fahrenheit.
    map ও lambda ব্যবহার করে Celsius-এর list-কে Fahrenheit-এ রূপান্তর করুন।
    ✨ Show Answer
    ans2.py
    celsius = [0, 20, 30, 37, 100]
    fahr = list(map(lambda c: c * 9/5 + 32, celsius))
    print(fahr)
  3. Recursively sum the digits of an integer, e.g. sum_digits(12345) == 15.
    Recursive ভাবে একটি integer-এর অঙ্কের যোগফল বের করুন।
    ✨ Show Answer
    ans3.py
    def sum_digits(n):
        if n < 10:
            return n
        return n % 10 + sum_digits(n // 10)
    
    print(sum_digits(12345))   # 15
  4. Use filter to keep only words longer than 4 letters from a list.
    filter দিয়ে ৪ অক্ষরের বেশি word-গুলো রেখে দিন।
    ✨ Show Answer
    ans4.py
    words = ["dog", "elephant", "cat", "tiger", "ox"]
    long_words = list(filter(lambda w: len(w) > 4, words))
    print(long_words)
  5. 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.

Recursion — সমস্যাকে তার ছোট সংস্করণে প্রকাশ করা; base case অবশ্যই লাগবে। Python-এর default limit ১০০০ — বড় input-এ iteration বা @lru_cache ব্যবহার করুন। lambda একটি ছোট anonymous function — বিশেষভাবে sorted, map, filter-এ উপযোগী।

Next Module → Strings — Deep Dive: indexing, slicing, 30+ methods, immutability, UTF-8।