The Fibonacci Series in Python

What is the output of this code snippet?


def fibo(n):
result = []
a, b = 0, 1
while a < n:
a, b = b, a+b
return result

fib100 = fibo(100)


Recap, the Fibonacci series is the series of numbers that arises when repeatedly summing up the last two numbers starting from 0 and 1. The fibo function in the puzzle calculates all Fibonacci numbers up to the function argument n. We use the concise method of multiple assignment to store the value of b in the variable a and to calculate the new value of b as the sum of both. We maintain the whole sequence in the list variable result by appending the sequence value a to the end of the list.

The puzzle calculates the Fibonacci sequence up to 100 and stores the whole list in the variable fib100. But to solve the puzzle, you do not have to calculate the whole sequence. The print statement only compares whether the last element is equal to the sum of the second and third last element in the sequence. This is true by definition of the Fibonacci series.

Humans can solve this puzzle easily using logic and strategic thinking. The Python interpreter, however, must take the brute-force approach of calculating everything from scratch. This nicely demonstrates your role as a computer programmer. You are the leading hand with unlimited power at your fingertips. But you must use your power wisely because the computer will do exactly what you ask him to do.

Are you a master coder?
Test your skills now!

Related Video




Leave a Comment

Your email address will not be published. Required fields are marked *