forked from firstcoder55/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci.py
More file actions
32 lines (20 loc) · 815 Bytes
/
Copy pathfibonacci.py
File metadata and controls
32 lines (20 loc) · 815 Bytes
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
"""solutions to the fibonacci problem"""
def fibonacci_iterative(limit):
"""fibonacci sequence using an iterative approach."""
a, b = 0, 1
for i in xrange(limit):
a, b = b, a + b
return a
def fibonacci_recursive(limit):
"""fibonacci sequence using a recusive approach."""
if limit <= 1:
return limit
return fibonacci_recursive(limit - 1) + fibonacci_recursive(limit - 2)
def fibonacci_reduce(limit):
"""fibonacci sequence using reduce (shortest option)."""
return reduce(lambda x, y: x + [x[y] + x[y - 1]], range(1, limit), [0, 1])[-1]
def fibonacci_comprehension(limit):
"""fibonacci sequence using a list comprehension."""
sequence = [0, 1]
[sequence.append(sequence[i] + sequence[i-1]) for i in range(1, limit)]
return sequence[-1]