beginner question fibonacci

J

Joon

.... # the sum of two elements defines the next
.... a, b = 0, 1.... print b
.... a, b = b, a+b
....
1
1
2
3
5
8


print b
a = b
b = a+b


1
2
4
8

Why a, b = b, a+b isn't a = b; b = a+b ?
 
M

Michael Hoffman

Joon said:
print b
a = b
b = a+b


1
2
4
8

Why a, b = b, a+b isn't a = b; b = a+b ?

Because you changed a before you added it to b.

Let's call your existing a and b "a0" and "b0", and the next a and b
"a1" and "b1". When you do a, b = b, a+b you are assigning:

a1 = b0
b1 = a0 + b0

But when you use separate statements, you are assigning:

a1 = b0
b1 = a1 + b0 = b0 + b0 = 2*b0
 
R

Robert Kern

Joon said:
... # the sum of two elements defines the next
... a, b = 0, 1
... print b
... a, b = b, a+b
...
1
1
2
3
5
8

print b
a = b
b = a+b

1
2
4
8

Why a, b = b, a+b isn't a = b; b = a+b ?

It's actually equivalent to:

temp = (b, a+b)
a = temp[0]
b = temp[1]

The temporary tuple object is created first, with the old values of a
and b. Then a and b are reassigned. The value of a doesn't change until
*after* a+b is calculated.

--
Robert Kern
(e-mail address removed)

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
 
R

ralobao

The case is that Python in attribution commands solves first the right
side, so he atributes the vars.

So the a+b expression is executed first.

Joon escreveu:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top