-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibonacci_sequence.py
74 lines (62 loc) · 1.47 KB
/
fibonacci_sequence.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
74
# Fibonacci sequence:
# https://www.mathsisfun.com/numbers/fibonacci-sequence.html
def fib(n):
if n == 0:
return 0
if n == 1:
return 1
if n > 1:
# note the repeated computations
return fib(n - 1) + fib(n - 2)
def fib_iterative(n):
if n == 0:
num = 0
elif n == 1:
num = 1
else:
n_1, n_2 = 1, 0
for i in range(2, n + 1):
num = n_1 + n_2
n_1, n_2 = num, n_1
return num
def fib_iterative2(n):
if n == 0:
num = 0
elif n == 1:
num = 1
else:
n_1, n_2 = 1, 0
i = 2
while i <= n:
num = n_1 + n_2
n_1, n_2 = num, n_1
i += 1
return num
def fib_iterative3(n):
if n == 0:
return 0
if n == 1:
return 1
i = 1
a, b = 0, 1
while True:
# advance a and b in a single iteration
a, b = b, a + b
i += 1
if i == n:
break
return b
if __name__ == "__main__":
# recursive
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
recursive = [fib(i) for i in range(11)]
assert expected == recursive
# iterative
iterative = [fib_iterative(i) for i in range(11)]
assert expected == iterative
# iterative 2
iterative_2 = [fib_iterative2(i) for i in range(11)]
assert expected == iterative_2
# iterative 3
iterative_3 = [fib_iterative3(i) for i in range(11)]
assert expected == iterative_3