python fibonacci - what is the difference? [duplicate] - python

This question already has answers here:
Python variable assignment question
(6 answers)
Closed 6 years ago.
I am learning python and I have some question:
What is the difference between
a,b = 0,1
for x in range(100):
print(a)
a=b
b=a+b
and
a,b = 0,1
for x in range(100):
print(a)
a,b = b, a+b
First one gives bad result, but why?

Because you first set a = b, your new b will have the value of twice the old b. You overwrite a to early. A correct implementation should use a temporary variable t:
a,b = 0,1
for x in range(100):
print(a)
t=a
a=b
b=t+b
This is basically what you do by using sequence assignment.
In your original code you have:
a,b = 0,1
for x in range(100):
print(a)
a=b # a now is the old b
b=a+b # b is now twice the old a so b'=2*b instead of b'=a+b
So this would result in jumping by multiplying with two each time (after first loading in 1 into a the first step).
An equivalent problem is the swap of variables. If you want a to take the value of b and vice versa, you cannot write:
#wrong swap
a = b
b = a
Because you lose the value of a after the first assignment. You can use a temporary t:
t = a
a = b
b = t
or use sequence assignment in Python:
a,b = b,a
where a tuple t = (b,a) is first created, and then assigned to a,b.

Related

Why Python can achieve a, b = b, a [duplicate]

This question already has an answer here:
How does swapping of members in tuples (a,b)=(b,a) work internally?
(1 answer)
Closed 1 year ago.
If we need to swap variables a and b in C or Java, we need to have something (pseudo code) like:
tmp = a;
a = b;
b = tmp;
Why Python can do it by a, b = b, a. What happened with it?
Not sure whether it is the right place for this question. But I do appreciate it if someone could give me some clues.
It's because python provides a special "tuple unpacking" syntax that many other languages don't have. I'll break apart what's going on:
The b, a on the right of the equals is making a tuple (remember, a tuple is pretty much the same as a list, except you can't modify it). The a, b on the left is a different syntax that's unpacking the tuple, i.e. it takes the first item in the tuple, and store it in the first variable listed, then it takes the second item and stored it in the second variable, and so forth.
This is what it looks like broken up in multiple steps:
a = 2
b = 3
my_tuple = a, b
print(my_tuple) # (2, 3)
b, a = my_tuple
print(a) # 3
print(b) # 2
And here's another, simpler examples of tuple unpacking, just to help wrap your mind around it:
x, y, z = (1, 2, 3)
print(x) # 1
print(y) # 2
print(z) # 3
By the way, Python's not the only one, Javascript can do it too, but with arrays:
[a, b] = [b, a];

Python aliasing [duplicate]

This question already has answers here:
If two variables point to the same object, why doesn't reassigning one variable affect the other?
(4 answers)
Are Python variables pointers? Or else, what are they?
(9 answers)
Closed 2 years ago.
I understand that given this code
a = [1,2,3]
b = [4,5,6]
c = a
and then by doing this
a[0] = 0
I wil change first positions of both a and c. Could somebody explain why this doesn't apply when I do this:
a = b
ie. why c doesn't become equal to b?
a = [1,2,3]
b = [4,5,6]
# a ────────> [1,2,3]
# b ────────> [4,5,6]
c = a # Changing 'c' to point at the list that 'a' points at
# c ─────┐
# a ─────┴──> [1,2,3]
# b ────────> [4,5,6]
a = b # Changing 'a' to point at the list that 'b' points at
# c ─────┐
# a ──┐ └──> [1,2,3]
# b ──┴─────> [4,5,6]
Because python interprets the line of code from the beginning of the code to the bottom line. Therefore, you have been assigned the b to a, after assigning a to c. The value of c is not changed until reassigning c.

Difference between defining multiple variable at a time and individually

I am a newbie in Python and I'm trying to learn Python through self-learning. I was trying to build Fibonacci series using a while loop. Here is my code, which doesn't return the desired result. Could anyone explain the problem?
a = 0
b = 1
while b<100:
print(b)
a = b
b = a + b
If we define a, b simultaneously like a, b = b, a+b, this works perfectly. Why is this happening? I don't understand because in both cases I am defining a and b the same way.
This is because programming languages like Python, and many others, execute the statements you write in the order you write them.
This means that by the time you execute b = a + b, the value of a has already changed in the previous line.
An easy way to solve this would be using a third variable to store the results temporarily.
a = 0
b = 1
c = 1
while c < 100:
print(c)
c = a + b
a = b
b = c
You are making one small mistake.
When you do a = b, you are changing the value of a. After this, when you do b=a+b, it is actually equivalent to b = b+b => b=2b.
To avoid this, use a temporary variable temp and storethe value of a in it. Then change the value of a using a = b. Then do, a = a+b.
Following is the code:
a=0
b=1
while b<100:
print(b)
temp = a
a = b
b = temp+b
When you do a, b = b, a+b, the previous value of a is used for calculating the new b, we have don a similar thing above by storing the previous value of a in temp
Operator "comma" (,) in Python is used to create a tuple, and it is allowed to omit the parentheses that surround a tuple. The expression a, b = b, a+b is actually an assignment of one tuple to another:
(a, b) = (b, a + b)
This statement is executed by evaluating the tuple constructor on the right-hand side (b, a + b). At this point, a new anonymous tuple (let's call it c) is created and the original values of a and b are not needed anymore. The tuple is then assigned elementwise to the tuple on the left-hand side. The new value of a becomes c[0] (that is, former b) and the new value of b becomes c[1] (that is, former a+b).
Your code is not working because you are changing the value of a before evaluating b. In the Fibonacci series, you want the previous value of a and b. You can use list as above or can introduce another variable to store values.
while True:
temp = a + b
if temp >100:
break
print(temp)
a = b
b = temp
For reference, here is a simple implementation using list:
lst = [0, 1]
while True:
temp = lst[-1]+lst[-2]
if temp>100:
break
lst.append(temp)
print(lst)

What does this construct do? [duplicate]

This question already has answers here:
Is there a standardized method to swap two variables in Python?
(8 answers)
Closed 6 years ago.
Example
num = [0,3,5,3,0,0,9,8]
Output should be
[3,5,3,9,8,0,0,0]
The solution to this in Python is
def moveZeroes(self, nums):
zero, cur = -1, 0
while cur < len(nums):
if nums[cur] != 0:
# update zero index when current is not zero
zero += 1
nums[cur], nums[zero] = nums[zero], nums[cur]
cur += 1
My question is I have seen similar statement like this a lot
nums[cur], nums[zero] = nums[zero], nums[cur]
What is this statement in particular doing?
The idiom
>>> a, b = b, a
swaps the values hold in a and b in one step so that a now points to the value that b used to point to, et vice versa:
>>> a, b = 1, 2
>>> a
1
>>> b
2
>>> a, b = b, a
>>> a
2
>>> b
1
Technically, the right-hand side creates a throwaway tuple, and the left-hand side is a tuple-unpacking assignment.
nums[cur], nums[zero] = nums[zero], nums[cur]
then means "swap the elements at index zero and at index cur.
This code nums[cur], nums[zero] = nums[zero], nums[cur] is swapping two values in the nums array. It is the same as if you had written:
temp = nums[cur]
nums[cur] = nums[zero]
nums[zero] = temp
When you use commas on both sides of the = assignment operator, Python essentially makes all of the assignments at once, so you don't need a temp variable.
It is swapping the values.
a, b = b, a
Now a has the value of b, and b has the value of a
This is Python's tuple packing and unpacking feature.
It's functionally identical to
temp = nums[cur]
nums[cur] = nums[zero]
nums[zero] = temp
but more efficient to the computer and more readable to programmers.
Further reading: https://stackoverflow.com/a/14836456/5399734
It's a variable swap, Python-style. It constructs a tuple of two values, the values at zero and cur, then unpacks that tuple and assigns the values to the indices at cur and zero; by reversing the indices assigned to, it swaps the values.
Note that the code could be simplified dramatically (though possibly at the expense of running slightly slower) by repurposing the key argument of the sort method to let Python do the work at the C layer:
def moveZeroes(self, nums):
nums.sort(key=lambda x: x == 0)
# Or more efficiently but obscurely:
# nums.sort(key=(0).__eq__)
# Or with an operator import to get speed with less obscurity:
# nums.sort(key=operator.not_)
Since Python's TimSort algorithm is stable, this preserves the order for all the non-zero values while moving the zeroes to the end.
It is first evaluating both of the values on the right, then it is substituting them to the matching slots on the left. So basically:
a, b = b, a
is like:
c = b
d = a
a = c
b = d
It is particularly useful to swap values or perform some operations on them without creating additional variables.

Difference between list assignment [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 7 years ago.
Help me understand difference between list assignment.
I have found that assignment like this
a[0] = b[0]
b[0] = a[0]
Is different from
a[0], b[0] = b[0], a[0]
The values of a and b in both the cases are different , however both of these assignment methods does the same , swapping.
You can run my sample code to see this
a = [0,1,2]
b = [3,4,5]
print "Value of a and b before swaping :"
print "value of a :" , a
print "value of b :" , b
print "\nswap in two line"
a[0] = b[0]
b[0] = a[0]
print "value of a :" , a
print "value of b :" , b
print "\nswap in one line"
# Reinitilizing value of a and b before performing swaping
a = [0,1,2]
b = [3,4,5]
a[0], b[0] = b[0], a[0]
print "value of a :" , a
print "value of b :" , b
How are two methods of assignment different? At the first glance they look the same and do the same thing.
however both of these assignment methods does the same [thing], swapping.
Not quite... The former example doesn't swap. Instead, it takes the first element of b and puts it in the first element of a. Then it takes the first element of a (which used to be the first element in b) and puts it back into b -- leaving a[0] and b[0] with the same value.
When it's all on the same line, python actually does something a little magical. It effectively creates a new tuple (b[0], a[0]) and then uses that tuple to assign things back into b and a. In other words, it behaves effectively the same as:
temp = (b[0], a[0])
a[0] = temp[0]
b[0] = temp[1]
notice how this is logically different from the first case you had.
The difference is the order in which assignment takes place. It has nothing to do with lists however.
The code
a = b
b = a
First assigns b to a, then assigns a to b resulting in both having the value that b had before.
On the other side
a, b = b, a
first evaluates b, a. And then take those values and assign to a and b. This results in a proper swap.

Categories