Fibonacci sequence python
Solution 1
a, b = b, a + b
This is known as multiple assignment. It's basically an atomic version of:
a = b
b = a + b
By atomic, I mean everything on the right is calculated before pacing it into the variables on the left. So a
becomes b
and b
becomes the old version of a
plus b
, equivalent to the non-atomic:
old_a = a
a = b
b = old_a + b
So, in terms of what you see:
a b output
================ ========================= ======
(initial values) (initial values)
0 1 1
(becomes prev b) (becomes sum of prev a,b)
1 1 1
1 2 2
2 3 3
3 5 5
5 8 8
That exact code (along with the explanation of multiple assignment) can be found here in the tutorial.
Solution 2
It's multiple assigment (or tuple unpacking).
According to Python Tutorial:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b
...
1
1
2
3
5
8
This example introduces several new features.
The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
Solution 3
How about multiple answers?
def fib(num):
a = 0
b = 1
while b <= num:
prev_a = a
a = b
b = prev_a +b
#print b
return a
print fib(13)
def pythonic_fib(num):
a,b = 0,1
while b <= num:
a,b = b, a+b
return a
print pythonic_fib(13)
def recursive_fib(num, a, b):
if (b >= num):
return b
else:
return recursive_fib(num, b, a+b)
print recursive_fib(13, 0, 1)
Solution 4
I know this is an old question, but just thought I'd through in my 2-cents since a lot of these seem a bit overly complicated for just the fibonacci sequence (outside the given answer), in case someone was still looking. You could do this:
a=1
b=0
while b<400:
a=a+b
b=a+b
print(a)
print(b)
This will give the desired output of the sequence(to whatever you set b less than).
eLg
Updated on December 25, 2020Comments
-
eLg over 3 years
I am trying to understand Python, but I still don't get it. I am new to the language, and wants to understand it properly. This is a line from a Fibonacci sequence using loops. Please explain the meaning of this code. I am trying to get the pattern by hand. I got the pattern up to 3, but after 3 I am not getting the answer.
a, b = 0, 1 while b < 50: print(b) a, b = b, a + b