Reputation: 109
I've just written these codes but outputs are different. second code's output is correct that I expected, but the first code's output is incorrect. but why?
def fib(n):
x = 0
y = 1
print x
for i in range(n):
x = y
y = x+y
print x
return x
output is; when n = 5
0
1
2
4
8
16
def fib(n):
x,y = 0,1
print x
for i in range(n):
x,y = y,x+y
print x
return x
output is; when n = 5
0
1
1
2
3
5
second code is correct but,
x,y = y,x+y
and
x = y , y = x+y
they look like same but outputs are different why?
Upvotes: 1
Views: 1896
Reputation: 1
If you want to go without tuple, you'll have to assign the value of x to a new variable z before updating it with the value of y and use this new variable to calculate the value of y. The code is from a different problem, but the output is a Fibonacci sequence.
x = 0
y = 1
print(x)
while y < 50:
print(y)
z = x
x = y
y = z+y
Upvotes: 0
Reputation: 2355
The difference is that you will update x and then use it in the first example and you will directly use it in the second example.
x, y = 0, 1
x = y # after this line x will be 1
y = x + y # y = 1 + 1
Second example
x,y = 0, 1
x,y = y,x+y # x, y = (1, 0 + 1) the old value of x will be used
This is because it will first generate the tuple on the right-hand side and after that, the tuple in your case (1, 1)
will be assigned to x
and y
Upvotes: 1
Reputation: 36
They give different outputs because with x=y, then y=x+y, you are setting x to the value of y. Then you take x, once its value has been updated and add it to y to find the y variable. With the one line variable declaration (x,y=y,y+x) in the y = y+x part of the equation, it will use a previous value of x instead of what you set it to in that line.
If you had:
x=0
y=1
Then you tried the one line declaration, it would look like this:
x,y=1,0+1
x,y=y,x+y
I hope this helped :)
Upvotes: 1