Problem: Print all Fibonacci numbers till n. The sequence F(n) of Fibonacci numbers is defined by the recurrence relation:
F(n) = F(n-1) + F(n-2)
with seed values
F(0) = 0, F(1) = 1.
Example:
0 1 1 2 3 5 8 13 21 34 55 89 ...
Solution in Python:
def fibonacci(n):
"""
Author: Mayur P Srivastava
"""
x = 0
y = 1
numbers = []
while x <= n:
numbers.append(x)
z = x + y
x = y
y = z
print numbers
Concepts learned: Single loop.
No comments:
Post a Comment