Sharing part of a function

Cecil Westerhof Cecil at decebal.nl
Sun Apr 3 17:27:21 EDT 2022


Betty Hollinshead <lizzyhollins99 at gmail.com> writes:

> "Memoising" is the answer -- see "Python Algorithms" by Magnus Lie Hetland.
> In the mean time, here a simplified version of "memoising" using a dict.
> This version handles pretty large fibonacci numbers!
>
> # fibonacci sequence
> # memoised - but using a simple dictionary (see Python Algorithms, p177)
>
> memo    = {}
> memo[1] = 1
> memo[2] = 2
>
> def fib(n):
>     if n in memo:
>         return memo[n]
>     else:
>         memo[n] = fib(n - 1) + fib(n - 2)
>         return memo[n]
>
>
> print(100, fib(100))
> print(memo)

No, it is not. It is the answer on a completely different question.
Nice, but not what I was asking about. And there is even an error in
the solution.

By the way: it is better to do it iterative. Try (when not done a
calculation before) fib(3_000).

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof


More information about the Python-list mailing list