This exercise is about creating the Fibonacci sequence using various methods. The aim is to come up with solutions that use different thinking.
What is Fibonacci sequence?
Fibonacci sequence is a sequence in which each number is the sum of the two preceeding ones. Click here to learn more.
Method 1:
Since the numbers in the Fibonacci sequence are the sum of the two numbers before them, we must have the first two numbers to start with.
fib_nums = [0, 1]
print(fib_nums)
[0, 1]
Then we can write a for loop to calculate the rest of the numbers and append them to fib_nums list. Let's say we want only the first 10 elements of the series.
for i in range(2, 10):
next_num = fib_nums[i-1] + fib_nums[i-2]
fib_nums.append(next_num)
print(fib_nums)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Method 2:
Is it possible to create the sequence without defining an initial list containing the first two elements before the for loop? In other words, can we obtain the first two elements within the for loop?
del(fib_nums)
for i in range(10):
if i == 0:
fib_nums = [i]
elif i == 1:
fib_nums.append(i)
else:
num = fib_nums[-1] + fib_nums[-2]
fib_nums.append(num)
print(fib_nums)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Method 3:
What about using a list comprehension?
del(fib_nums)
fib_nums = [0, 1]
[fib_nums.append(fib_nums[-1]+fib_nums[-2]) for i in range(2, 10) if i > 1]
print(fib_nums)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Method 4
A more pythonic approach: Define a function that creates a generator using the keyword yield to return an iterator object.
# define a generator function
def fib_num_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# convert the output of fib_num_generator function into a list
fib_nums = list(fib_num_generator(10))
print(fib_nums)
# Or loop over generator function and save the output as a list
fib_nums = [num for num in fib_num_generator(10)]
print(fib_nums)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]