Decorators not worth the effort

Chris Angelico rosuav at gmail.com
Fri Sep 14 13:30:12 EDT 2012


On Sat, Sep 15, 2012 at 2:15 AM, andrea crotti
<andrea.crotti.0 at gmail.com> wrote:
> The poor algorithm is much more close to the mathematical definition
> than the smarter iterative one..  And in your second version you
> include some ugly caching logic inside it, so why not using a
> decorator then?

I learned Fibonacci as a sequence, not as a recursive definition. So
the algorithm I coded (the non-caching one) is pretty much how I
learned it in mathematics. But yes, you're right that the caching is
inherent to the second version; and yes, that's where a decorator can
make it a LOT cleaner.

As a demo of recursion and decorators, your original function pair is
definitely the best. But if you want to be able to calculate fib(n)
for any n without blowing your stack, my version will scale much more
safely.

But then again, who actually ever needs fibonacci numbers?

ChrisA



More information about the Python-list mailing list