+ 1

How can a recursive function works perfectly in a for loop with large numbers while calling it too many times raises an error?

What I know is, a recursive function is a function that calls itself multiple times. It raises a RecursionError if it is called too many times. However, in the code example below, the fib() function works perfectly inside a for loop that iterates from 1 to 2000, while calling it outside the loop, passing only 1000 to it immediately raises a RecursionError. Can someone explain me why? https://sololearn.com/compiler-playground/ctNkN4ckuEjK/?ref=app

14th Feb 2025, 12:23 PM
Dragon RB
Dragon RB - avatar
10 odpowiedzi
+ 4
Dragon RB Ah okay, then it's probably because of that lru_cache, that prevents a stack overflow.
14th Feb 2025, 3:50 PM
Jan
Jan - avatar
+ 3
Dragon RB The lru cache seems to work better if used repeatedy in the for loop. Jan , i was thinking the same thing, but I modified the code to be able to see the end values and it seems to be performing better inside the for loop. I played around with the code a bit... clearing the cache after each iteration stopped the strange performance boost. perhaps some memory swapping is happening which allows the cache to store the bigger values in the for loop as opposed to the fib function being called only once when it's outside the for loop... not sure. https://sololearn.com/compiler-playground/chW9m3fjo6p4/?ref=app
15th Feb 2025, 9:09 AM
Bob_Li
Bob_Li - avatar
+ 2
Bob_Li I can only speak for myself now, but the best thing is to avoid recursive functions.
15th Feb 2025, 10:14 AM
Jan
Jan - avatar
+ 2
Jan agreed. it's easy to write, but often resource-heavy to execute.
15th Feb 2025, 12:19 PM
Bob_Li
Bob_Li - avatar
+ 1
It only works perfect in the loop because of "Execution Timet Out" when it reach 70 in the loop. It's the limitation on the playground that prevents it from causing a stack overflow. If you run the code on a pc, then you would probably quite quickly get a stack overflow.
14th Feb 2025, 3:06 PM
Jan
Jan - avatar
+ 1
Jan Nope! I ran the code on my IDE.
14th Feb 2025, 3:31 PM
Dragon RB
Dragon RB - avatar
+ 1
Bob_Li and Jan , you guys are stars! Thanks for your efforts and sharing of knowledge.
15th Feb 2025, 4:37 PM
Ausgrindtube
Ausgrindtube - avatar
0
My understanding is that recursion can be fairly intensive on resources, so maybe that's what occurs here. I think I read some good threads here about it: https://www.sololearn.com/discuss/1671835/?ref=app https://www.sololearn.com/discuss/307407/?ref=app https://www.sololearn.com/discuss/120350/?ref=app
14th Feb 2025, 1:07 PM
Ausgrindtube
Ausgrindtube - avatar
0
What happened
15th Feb 2025, 7:46 AM
Sagar Battula
Sagar Battula - avatar
0
+++++
15th Feb 2025, 7:47 AM
Sagar Battula
Sagar Battula - avatar