ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
မြန်မာ ယောက်ချင်းထိုး ရုပ်တွေ (matryoshka doll) ကို စဉ်းစားကြည့်ပါ။ အရုပ်ကို ဖွင့်လိုက်တိုင်း အထဲမှာ ပိုသေးတဲ့ အရုပ်တစ်ရုပ် ရှိပါတယ်။ ဖွင့်လို့ မရတော့တဲ့ အသေးဆုံးအရုပ်ကို ရောက်မှ ရပ်ပါတယ်။
Recursion လည်း အဲဒီလိုပါပဲ။ Function က ပြဿနာကြီးကို ကိုယ်တိုင် မဖြေရှင်းဘဲ "ပိုသေးတဲ့ ပြဿနာကို ကိုယ့်ကိုယ်ကိုယ် ပြန်မေးကြည့်မယ်" လို့ ပြောပါတယ်။ အသေးဆုံးအရုပ်က base case ပါ။ အဖြေကို တိုက်ရိုက်သိလို့ ထပ်မခေါ်တော့ပါဘူး။ Base case မရှိရင် ဒါမှမဟုတ် အရုပ်တွေ သေးမလာရင် ဖွင့်တာ ဘယ်တော့မှ မပြီးပါဘူး။
Problem → Why → Solution
ပြဿနာ: base case ရှိပေမဲ့ ဘယ်တော့မှ မရောက်တာ
အောက်က countdown() မှာ if n == 0 ဆိုတဲ့ base case ပါပါတယ်။ countdown(3) ဆိုရင် မှန်ပါတယ်။ ဒါပေမဲ့ user က 2.5 ဒါမှမဟုတ် -1 ပေးလိုက်ရင် n က 0 ကို တိုက်ရိုက် ဘယ်တော့မှ မထိဘဲ 1.5၊ 0.5၊ -0.5... ဒါမှမဟုတ် -2၊ -3... ဆိုပြီး ဆက်ဆင်းသွားပါတယ်။
ခဏကြာတော့ RecursionError: maximum recursion depth exceeded နဲ့ program ရပ်သွားပါတယ်။ Base case ရေးထားပြီးပြီဆိုပြီး စိတ်ချနေခဲ့ပေမဲ့ call တိုင်းက base case ဆီ တကယ် ရောက်မရောက်ကို မစစ်ခဲ့မိပါဘူး။
def countdown(n):
if n == 0: # base case exists ...
print("Done!")
return
print(n)
countdown(n - 1) # ... but 2.5 or -1 skips right past 0
countdown(-1) # RecursionError: maximum recursion depth exceededဘာကြောင့် ဒီလိုဖြစ်တာလဲ
Recursion မှန်ဖို့ base case ရှိရုံနဲ့ မလုံလောက်ပါဘူး။ Call တိုင်းက base case ဆီ တိုးတက်ရမယ် (progress) ဆိုတဲ့ အာမခံချက် လိုပါတယ်။ n == 0 လို တိကျတဲ့ စစ်ချက်က input တချို့ကို ကျော်သွားစေနိုင်ပါတယ်။ n <= 0 လို အကွာအဝေး စစ်ချက်ကို သုံးတာ ဒါမှမဟုတ် မမှန်တဲ့ input ကို အစကတည်းက ငြင်းတာက ပိုလုံခြုံပါတယ်။ Python ကလည်း call stack ကို အကန့်အသတ်နဲ့ ထားလို့ infinite recursion က RecursionError အဖြစ် ပေါ်လာပါတယ်။
Core concept: call stack ပေါ်က recursion
Function ကို ခေါ်တိုင်း Python က stack frame အသစ်တစ်ခု ဆောက်ပါတယ်။ Frame ထဲမှာ အဲဒီ call ရဲ့ parameter နဲ့ local variable တွေ သိမ်းထားပါတယ်။ factorial(3) က factorial(2) ကို ခေါ်တဲ့အခါ ပထမ frame က မပြီးသေးဘဲ စောင့်နေပါတယ်။ Base case ကို ရောက်တော့မှ အဖြေတွေက frame တစ်ခုချင်းကို ပြန်တက်လာပြီး စောင့်နေတဲ့ multiplication တွေ ပြီးသွားပါတယ်။
factorial(3) on the call stack
------------------------------
going down (calls) coming back (returns)
factorial(3) waits for 3 * ? 3 * 2 = 6 -> final answer
factorial(2) waits for 2 * ? 2 * 1 = 2 -> returned to (3)
factorial(1) base case returns 1 -> returned to (2)၁။ Base case: အဖြေကို တိုက်ရိုက်ပြန်ပေး
အသေးဆုံး input (n <= 1၊ ဗလာ list၊ child မရှိတဲ့ node) အတွက် ထပ်မခေါ်ဘဲ အဖြေကို ပြန်ပေးပါ။ Base case ကို function ရဲ့ အပေါ်ဆုံးမှာ ရေးတာ ဖတ်ရလွယ်ပါတယ်။
၂။ Recursive case: ပိုသေးတဲ့ ပြဿနာကို ခေါ်
n - 1၊ list ရဲ့ ကျန်တဲ့အပိုင်း၊ child node လိုမျိုး base case ဆီ တစ်လှမ်းနီးတဲ့ input နဲ့ ပြန်ခေါ်ပါ။ ရလာတဲ့ အဖြေကို လက်ရှိ အလုပ်နဲ့ ပေါင်းစပ်ပါ (n * ...၊ size += ...)။
၃။ ထပ်ခါတလဲလဲ အလုပ်ကို သတိထားပါ
fib(n) က fib(n-1) နဲ့ fib(n-2) ကို ခေါ်ပြီး နှစ်ခုစလုံးက တူညီတဲ့ subproblem တွေကို ထပ်ခါထပ်ခါ တွက်ပါတယ်။ fib(20) တစ်ခုတည်းအတွက် call ပေါင်း 21,891 ခု ဖြစ်ပါတယ်။ @lru_cache နဲ့ ရလဒ်ကို မှတ်ထားရင် n တစ်ခုစီကို တစ်ခါပဲ တွက်ပါတယ်။
၄။ Depth limit ကို လေးစားပါ
CPython ရဲ့ default recursion limit က 1000 ဖြစ်ပြီး tail call optimization မလုပ်ပါဘူး။ Linked list ဒါမှမဟုတ် ရှည်လျားတဲ့ chain လို level ထောင်ချီ နက်နိုင်တဲ့ data အတွက် list ကို stack အဖြစ်သုံးတဲ့ loop နဲ့ ရေးပါ။ sys.setrecursionlimit() နဲ့ limit မြှင့်တာက C stack ကို overflow ဖြစ်စေပြီး process တစ်ခုလုံး crash ဖြစ်နိုင်လို့ နောက်ဆုံးနည်းပဲ ဖြစ်ပါစေ။
ဒါဆို recursion ကို ဘယ်အချိန် ရွေးမလဲ။ Data ကိုယ်တိုင်က recursive ပုံသဏ္ဌာန် ရှိတဲ့အခါ (folder ထဲမှာ folder၊ category ထဲမှာ category) ဒါမှမဟုတ် ပြဿနာကို တစ်ဝက်စီ ခွဲပြီး ဖြေရှင်းတဲ့ divide-and-conquer algorithm (merge sort၊ binary search) တွေမှာ recursion က အရှင်းဆုံးပါ။ 1 ကနေ n အထိ ရေတွက်တာလို ဖြောင့်ဖြောင့်တန်းတန်း အလုပ်တွေအတွက်တော့ for loop က ပိုမြန်ပြီး ပိုရှင်းပါတယ်။
- Base case ဆိုရင် တိုက်ရိုက် return
- မဟုတ်ရင် ပိုသေးတဲ့ input နဲ့ ခေါ်
- Frame တွေ stack ပေါ် စုသွား
- အဖြေတွေ ပြန်တက်လာပြီး ပေါင်းစပ်
Recursive call တစ်ခုကို "ဒီ function က ပိုသေးတဲ့ input အတွက် မှန်တယ်" လို့ ယုံပြီး လက်ရှိအဆင့်ကိုပဲ စဉ်းစားပါ။ ဒါကို recursive leap of faith လို့ ခေါ်ပါတယ်။
အခြေခံ ပုံစံ
def solve(problem):
if is_smallest(problem): # base case
return direct_answer(problem)
smaller = shrink(problem) # must move toward the base case
partial = solve(smaller) # recursive case
return combine(problem, partial)Recursive function တိုင်းက ဒီပုံစံပါ။ shrink() က base case ဆီ အမြဲ ရောက်အောင် လုပ်ရပြီး combine() က လက်ရှိအဆင့်ရဲ့ အလုပ်ကို ထည့်ပါတယ်။
ဥပမာ: countdown ကနေ folder tree အထိ
ဒီ script က countdown၊ factorial၊ Fibonacci ဥပမာတွေကို တစ်ခုချင်း လက်တွေ့ အသုံးဝင်အောင် ပြထားပါတယ်။ Fibonacci မှာ call အရေအတွက်ကို ရေတွက်ပြီး memoized version နဲ့ နှိုင်းယှဉ်ထားပါတယ်။ နောက်ဥပမာတစ်ခုက nested folder size ကို တွက်ပြီး နောက်ဆုံးမှာ recursion limit ကို ကျော်ရင် ဘာဖြစ်လဲ ပြပါတယ်။ factorial() က အနှုတ်ဂဏန်းကိုလည်း ValueError နဲ့ ငြင်းပါတယ်။
import sys
from functools import lru_cache
# ===== 1. Basic recursion: countdown =====
def countdown(n: int) -> None:
if n == 0: # base case: stop here
print("Done!")
return
print(n)
countdown(n - 1) # recursive case: a smaller problem
print("===== Countdown =====")
countdown(3)
# ===== 2. Factorial: combine results on the way back =====
def factorial(n: int) -> int:
if n < 0:
raise ValueError("factorial is undefined for negative numbers")
if n <= 1:
return 1
return n * factorial(n - 1)
print("\n===== Factorial =====")
print(f"5! = {factorial(5)}")
# ===== 3. Fibonacci: repeated work and memoization =====
calls = 0
def fib(n: int) -> int:
global calls
calls += 1
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
@lru_cache(maxsize=None)
def fib_memo(n: int) -> int:
if n <= 1:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print("\n===== Fibonacci =====")
print(f"fib(20) = {fib(20)} using {calls} calls")
print(f"fib_memo(20) = {fib_memo(20)}, cache misses: {fib_memo.cache_info().misses}")
# ===== 4. Recursion on nested data =====
def total_size(folder: dict) -> int:
size = sum(folder.get("files", []))
for child in folder.get("folders", []):
size += total_size(child)
return size
project = {
"files": [120, 30],
"folders": [
{"files": [500]},
{"files": [10, 5], "folders": [{"files": [2000]}]},
],
}
print("\n===== Nested folders =====")
print(f"Total size: {total_size(project)} KB")
# ===== 5. The depth limit =====
print("\n===== Depth limit =====")
print(f"Recursion limit: {sys.getrecursionlimit()}")
try:
factorial(5000)
except RecursionError:
print("factorial(5000) -> RecursionError")Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Base case first
if n == 0: # base case: stop herecountdown(3) က 3၊ 2၊ 1 ကို print ထုတ်ပြီး n က 0 ရောက်တော့ Done! ပြကာ return ပါတယ်။ ဒီ demo မှာ non-negative int ပဲ ပေးလို့ မှန်ပေမဲ့ problem section မှာ ပြခဲ့သလို input ကို အမြဲ မယုံပါနဲ့။
- Combine on the way back
return n * factorial(n - 1)n * ... က factorial(n - 1) ပြန်လာမှပဲ တွက်လို့ရပါတယ်။ ဒါကြောင့် frame တွေ stack ပေါ်မှာ စောင့်နေပြီး base case ကနေ 1၊ 2၊ 6၊ 24၊ 120 ဆိုပြီး ပြန်တက်လာပါတယ်။
- Two calls per level
return fib(n - 1) + fib(n - 2)Call တစ်ခုက call နှစ်ခု ထပ်ခေါ်လို့ call အရေအတွက်က exponential တိုးပါတယ်။ fib(20) အတွက် 21,891 ကြိမ် ဖြစ်ပြီး fib(40) ဆိုရင် သန်းရာချီ ဖြစ်ပါတယ်။
- Memoization decorator
@lru_cache(maxsize=None)lru_cache က argument တစ်ခုစီရဲ့ ရလဒ်ကို မှတ်ထားလို့ fib_memo(20) က 0 ကနေ 20 အထိ value 21 ခုကိုပဲ တကယ်တွက်ပါတယ် (cache miss 21 ခု)။ ကျန်တဲ့ call တွေက cache ထဲကနေ ချက်ချင်း ပြန်ရပါတယ်။
- Recursing into children
size += total_size(child)Folder တစ်ခုရဲ့ size က သူ့ file တွေ ပေါင်းခြင်းနဲ့ sub-folder တစ်ခုစီရဲ့ size ပေါင်းခြင်းပါ။ Sub-folder မရှိရင် for loop က ဘာမှ မလုပ်လို့ အဲဒါက base case ပါ။ ရလဒ် 2665 KB က file အားလုံးရဲ့ ပေါင်းခြင်းပါ။
- Hitting the limit
factorial(5000)Call 5000 ဆင့် လိုပေမဲ့ limit က 1000 ဖြစ်လို့ RecursionError တက်ပါတယ်။ Exception ကို ဖမ်းလို့ program ဆက်သွားပါတယ်။ math.factorial(5000) ကတော့ loop နဲ့ ရေးထားလို့ ပြဿနာ မရှိပါဘူး။
===== Countdown =====
3
2
1
Done!
===== Factorial =====
5! = 120
===== Fibonacci =====
fib(20) = 6765 using 21891 calls
fib_memo(20) = 6765, cache misses: 21
===== Nested folders =====
Total size: 2665 KB
===== Depth limit =====
Recursion limit: 1000
factorial(5000) -> RecursionErrorRecursion ကို loop နဲ့ explicit stack အဖြစ် ပြောင်းခြင်း
Recursion က Python ရဲ့ call stack ကို မသိမသာ သုံးပါတယ်။ အဲဒီ stack ကို list တစ်ခုနဲ့ ကိုယ်တိုင် ကိုင်လိုက်ရင် depth limit မရှိတော့ပါဘူး။ Pattern က ရိုးရှင်းပါတယ်: stack = [root] နဲ့ စ၊ while stack: ထဲမှာ node = stack.pop() လုပ်ပြီး node ကို process လုပ်၊ ပြီးရင် child တွေကို stack.extend() နဲ့ ထည့်ပါ။
Tree လို ပုံသဏ္ဌာန်ရှိတဲ့ data ပေါ်မှာ အလုပ်လုပ်တဲ့ recursive code က ဖတ်ရလွယ်ပါတယ်။ Data ရဲ့ depth ကို ကိုယ်မထိန်းနိုင်ရင် (user upload လုပ်တဲ့ JSON၊ ရှည်လျားတဲ့ chain) iterative version ကို ရွေးပါ။ Graph မှာ cycle ရှိနိုင်ရင် ရောက်ပြီးသား node တွေကို visited set နဲ့ မှတ်ထားဖို့ မမေ့ပါနဲ့။ မမှတ်ရင် recursive version ရော iterative version ပါ အဆုံးမရှိ လည်နေပါလိမ့်မယ်။
Standard library က recursion ကို ဖုံးပေးတဲ့နေရာ
Folder တွေကို လျှောက်ဖို့ os.walk() ဒါမှမဟုတ် pathlib.Path.rglob("*") ကို သုံးပါ။ Factorial အတွက် math.factorial()၊ JSON ကို ဖတ်ဖို့ json.loads() ကို သုံးပါ။ ကိုယ်တိုင် recursion ရေးတာက standard tool မရှိတဲ့ data structure တွေအတွက်ပဲ လိုပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Recursion က tree ပုံသဏ္ဌာန် data နေရာတိုင်းမှာ ပေါ်ပါတယ်။ E-commerce site ရဲ့ category tree (Books > Programming > Python)၊ comment တွေရဲ့ reply thread၊ organisation chart၊ HTML DOM၊ nested JSON config နဲ့ file system တွေပါ။ Breadcrumb ဆောက်တာ၊ sub-category အားလုံးထဲက product အရေအတွက် ရေတွက်တာ၊ menu ကို indentation နဲ့ ဆွဲတာတွေက recursive function တစ်ခုနဲ့ ရိုးရှင်းစွာ ရေးလို့ရပါတယ်။
Production မှာ data ရဲ့ depth ကို ကိုယ်မထိန်းနိုင်တာ များပါတယ်။ Admin တစ်ယောက်က category ကို သူ့ကိုယ်သူ parent အဖြစ် မှားသတ်မှတ်လိုက်ရင် cycle ဖြစ်ပြီး visited set မပါတဲ့ code က ရပ်မသွားတော့ပါဘူး။ ဒါကြောင့် team တွေက recursive version နဲ့ iterative version နှစ်ခုစလုံးကို ပုံမှန် tree၊ အလွန်နက်တဲ့ chain နဲ့ cycle ပါတဲ့ data နဲ့ test လုပ်လေ့ရှိပါတယ်။ Team အများအပြားက category တစ်ခုစီရဲ့ depth ဒါမှမဟုတ် path အပြည့်ကို database ထဲမှာ ကြိုသိမ်းထားလို့ အသုံးများတဲ့ page တွေမှာ request တိုင်း recursion လုပ်စရာ မလိုပါဘူး။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Recursive call ရဲ့ ရလဒ်ကို return မလုပ်တာ
def find(node, target): ... find(child, target) လို့ return မပါဘဲ ရေးရင် ရှာတွေ့ပေမဲ့ ရလဒ်က အပေါ် frame ကို မရောက်ဘဲ function က None ပြန်ပေးပါတယ်။ Recursive call ရဲ့ value ကို လိုတိုင်း return ဒါမှမဟုတ် variable ထဲ သိမ်းပါ။
Base case မှာ အတိအကျ တန်းတူစစ်တာ
if n == 0 က n က 1 စီ ကျမှပဲ ရောက်ပါတယ်။ n - 2 နဲ့ ခေါ်တဲ့ function၊ float input၊ အနှုတ်ဂဏန်း input တွေက 0 ကို ကျော်သွားပါတယ်။ if n <= 0 လို range စစ်ချက်ကို သုံးပြီး မမှန်တဲ့ input ကို အစမှာ ValueError နဲ့ ငြင်းပါ။
Default argument အဖြစ် mutable list ကို သုံးတာ
def collect(node, found=[]) လို့ ရေးရင် default list က call အားလုံး မျှသုံးလို့ ဒုတိယအကြိမ် collect() ခေါ်တဲ့အခါ ပထမအကြိမ်က item တွေ ကျန်နေပါတယ်။ found=None ထားပြီး function ထဲမှာ list အသစ် ဆောက်ပါ၊ ဒါမှမဟုတ် ရလဒ် list ကို return ပြီး ပေါင်းပါ။
Mini challenge
Category tree ကို လျှောက်ပါ
{"name": ..., "children": [...]} ပုံစံ category tree အတွက် recursive function သုံးခုနဲ့ iterative function တစ်ခု ရေးပါ။ ပြီးရင် level 5,000 ရှိတဲ့ chain တစ်ခုနဲ့ recursive နဲ့ iterative ကို နှိုင်းယှဉ်ပါ။
- count_nodes() က node အားလုံး (root ပါ) ကို ရေတွက်ရပါမယ်
- max_depth() က child မရှိတဲ့ node ကို depth 1 အဖြစ် ယူရပါမယ်
- find_path() က root ကနေ target အထိ နာမည် list ကို ပြန်ပေးပြီး မတွေ့ရင် None ပြန်ပေးရပါမယ်
- count_nodes_iterative() က list ကို stack အဖြစ် သုံးပြီး recursion မပါရပါ
Category = dict # {"name": str, "children": list[Category]}
def count_nodes(node: Category) -> int:
# TODO: 1 for this node + the count of every child subtree
...
def max_depth(node: Category) -> int:
# TODO: base case: no children -> 1
# TODO: otherwise 1 + the deepest child
...
def find_path(node: Category, target: str) -> list[str] | None:
# TODO: found here -> [name]; else try each child and prepend name
...
def count_nodes_iterative(root: Category) -> int:
# TODO: stack = [root]; pop, count, push children until empty
...
shop = {
"name": "Shop",
"children": [
{"name": "Books", "children": [{"name": "Python"}, {"name": "Poetry"}]},
{"name": "Music", "children": [
{"name": "Jazz", "children": [{"name": "Bebop"}]},
]},
],
}
# TODO: print node count, depth, the path to "Bebop" and to "Rock"
# TODO: build a 5,000-level chain and compare both counting functionsရလဒ်: Nodes: 7၊ depth: 4၊ Bebop ရဲ့ path က ['Shop', 'Music', 'Jazz', 'Bebop']၊ Rock ရဲ့ path က None ဖြစ်ပါမယ်။ Deep chain မှာ iterative က node 5001 ခု ရေတွက်ပြီး recursive က RecursionError ဖြစ်ပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
find_path() မှာ child တစ်ခုက None မဟုတ်တဲ့ path ပြန်ပေးတာနဲ့ [node["name"], *path] ကို ချက်ချင်း return ပါ။ Chain ကို loop နဲ့ ဆောက်ပါ၊ recursion နဲ့ မဆောက်ပါနဲ့။
အဖြေ ကြည့်ရန်
Category = dict # {"name": str, "children": list[Category]}
def count_nodes(node: Category) -> int:
return 1 + sum(count_nodes(child) for child in node.get("children", []))
def max_depth(node: Category) -> int:
children = node.get("children", [])
if not children:
return 1
return 1 + max(max_depth(child) for child in children)
def find_path(node: Category, target: str) -> list[str] | None:
if node["name"] == target:
return [node["name"]]
for child in node.get("children", []):
path = find_path(child, target)
if path is not None:
return [node["name"], *path]
return None
def count_nodes_iterative(root: Category) -> int:
stack = [root]
count = 0
while stack:
node = stack.pop()
count += 1
stack.extend(node.get("children", []))
return count
shop = {
"name": "Shop",
"children": [
{"name": "Books", "children": [{"name": "Python"}, {"name": "Poetry"}]},
{"name": "Music", "children": [
{"name": "Jazz", "children": [{"name": "Bebop"}]},
]},
],
}
print(f"Nodes: {count_nodes(shop)}, depth: {max_depth(shop)}")
print(f"Path to Bebop: {find_path(shop, 'Bebop')}")
print(f"Path to Rock: {find_path(shop, 'Rock')}")
deep = {"name": "level-0"}
current = deep
for i in range(1, 5001):
current["children"] = [{"name": f"level-{i}"}]
current = current["children"][0]
print(f"Deep chain (iterative): {count_nodes_iterative(deep)} nodes")
try:
count_nodes(deep)
except RecursionError:
print("Deep chain (recursive): RecursionError")Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Recursion မှာ base case၊ ပိုသေးတဲ့ subproblem နဲ့ base case ဆီ သေချာရောက်မယ့် progress လိုပါတယ်
- Call တိုင်း stack frame အသစ်ဖြစ်ပြီး အဖြေတွေက base case ကနေ ပြန်တက်လာပါတယ်
- ထပ်ခါတလဲလဲ subproblem တွေကို @lru_cache နဲ့ မှတ်ထားပါ
- CPython ရဲ့ default limit က 1000 ဖြစ်ပြီး tail call optimize မလုပ်လို့ နက်တဲ့ data အတွက် explicit stack သုံးပါ
- Tree နဲ့ nested data မှာ recursion က ရှင်းလင်းပြီး cycle ရှိနိုင်ရင် visited set ထည့်ပါ
Python Documentation — Functional Programming HOWTO — Python Software Foundation