Sharing part of a function
Betty Hollinshead
lizzyhollins99 at gmail.com
Sun Apr 3 14:00:33 EDT 2022
"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)
More information about the Python-list
mailing list