kristofer revisó este gist . Ir a la revisión
1 file changed, 5 insertions, 2 deletions
memoization.py
@@ -1,7 +1,10 @@ | |||
1 | - | # example of memoization in pythong for fibonacci | |
1 | + | # example of memoization in python for fibonacci | |
2 | 2 | ||
3 | 3 | # Memoization: Let’s Be Efficient, Shall We? | |
4 | - | # Ever ask the same question over and over? Annoying, right? That’s what your computer thinks too. Memoization fixes this by storing results so you don’t have to repeat expensive calculations. | |
4 | + | # Ever worry about recursion and the stack and so on... | |
5 | + | # Ever ask the same question over and over? | |
6 | + | # Annoying, right? That’s what your computer thinks too. | |
7 | + | # Memoization fixes this by storing results so you don’t have to repeat expensive calculations. | |
5 | 8 | def fib(n, memo={}): | |
6 | 9 | if n in memo: | |
7 | 10 | return memo[n] |
kristofer revisó este gist . Ir a la revisión
1 file changed, 15 insertions
memoization.py(archivo creado)
@@ -0,0 +1,15 @@ | |||
1 | + | # example of memoization in pythong for fibonacci | |
2 | + | ||
3 | + | # Memoization: Let’s Be Efficient, Shall We? | |
4 | + | # Ever ask the same question over and over? Annoying, right? That’s what your computer thinks too. Memoization fixes this by storing results so you don’t have to repeat expensive calculations. | |
5 | + | def fib(n, memo={}): | |
6 | + | if n in memo: | |
7 | + | return memo[n] | |
8 | + | if n < 2: | |
9 | + | return n | |
10 | + | memo[n] = fib(n - 1, memo) + fib(n - 2, memo) | |
11 | + | return memo[n] | |
12 | + | ||
13 | + | fib(100) | |
14 | + | ||
15 | + | # 354224848179261915075 |