can someone help me simplify this recursive function? I need to run cake(100) but anything past around 25 seems to crash.
>>61039266
nevermind I literally just fixed it using a dictionary
_cake = {}
def cake(t):
if t >100:
return (0,0)
else:
if t not in _cake:
_cake[t] = 0.01*t*(1- sum(cake(n) for n in range(t)))
return _cake[t]
https://youtu.be/ZVQYMSBPSOY // the answer
nigga you call cake(100) and you have:
>an array of 100 numbers
>100 calls from cake(0) to cake(99)
>so then you have
>>1+100 arrays of 0-100
>>10000 more calls, from cake(0) to cake(98)
I'm not surprised it all broke down.
>>61039325
i fixed it with a dictionary as per the first comment. why does that way work though?
>>61039266
Type in@lru_cache(max_size=None)
And also import it of course. Look it up.
def cake(t):
y = 0
ys = 0
for i in range(t + 1):
y = 0.01 * i * (1 - ys)
ys += y
return y
Although cake(100) is so small it just prints 0.0, last t that doesn't print zero is
73 : 8.104628079763643e-17
>>61039302
Congratulations you've just discovered dynamic programming. Well done OP
use logs
Don't do it recursively. Do it iteratively.
>>61041026
> recursion
> python
choose one
>>61039383
It's a classic case of "bad recursion". It's the same reason why Fibbonacci is slow when you write it recursively -- because there's a lot of duplicated effort if you plot out the call graph.
By using a dictionary you're memoising the function calls, removing the duplicated effort.