forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.py
73 lines (52 loc) · 1.45 KB
/
fibonacci.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Fibonacci tool
# This script only works with Python3!
import time
def getFibonacciIterative(n: int) -> int:
"""
Calculate the fibonacci number at position n iteratively
"""
a = 0
b = 1
for _ in range(n):
a, b = b, a + b
return a
def getFibonacciRecursive(n: int) -> int:
"""
Calculate the fibonacci number at position n recursively
"""
a = 0
b = 1
def step(n: int) -> int:
nonlocal a, b
if n <= 0:
return a
a, b = b, a + b
return step(n - 1)
return step(n)
def getFibonacciDynamic(n: int, fib: list) -> int:
"""
Calculate the fibonacci number at position n using dynamic programming to improve runtime
"""
if n == 0 or n == 1:
return n
if fib[n] != -1:
return fib[n]
fib[n] = getFibonacciDynamic(n - 1, fib) + getFibonacciDynamic(n - 2, fib)
return fib[n]
def main():
n = int(input())
fib = [-1] * n
getFibonacciDynamic(n, fib)
def compareFibonacciCalculators(n: int) -> None:
"""
Interactively compare both fibonacci generators
"""
startI = time.clock()
resultI = getFibonacciIterative(n)
endI = time.clock()
startR = time.clock()
resultR = getFibonacciRecursive(n)
endR = time.clock()
s = "{} calculting {} => {} in {} seconds"
print(s.format("Iteratively", n, resultI, endI - startI))
print(s.format("Recursively", n, resultR, endR - startR))