How to get correct answer in for loop - python

I want to do multiplication using for loop. Here is the code.
a = 4
b = 6
for i in [a,b]:
i*=2
The values of a and b remain the same. How to make it work?

int are immutable, so you'll need to rebind a and b to fresh int objects
>>> a = 4
>>> b = 6
>>> a, b = (i*2 for i in [a,b])
>>> a
8
>>> b
12

Use dictionary:
z = {'i': a, 'j': b}
for k in z.keys():
z[k] *= 2
a = z['i']
b = z['j']

Related

How does this Python Function evaluate the nth Fibbonacci number? [duplicate]

This is my first question and I started to learn Python.
Is there a difference between:
a, b = b, a + b
and
a = b
b = a + b
When you write it in below example it shows different results.
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
fib(1000)
and
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a = b
b = a + b
print()
fib(1000)
In a, b = b, a + b, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:
c = a + b
a = b
b = c
In the second example, the value of a has already been changed by the time b = a + b is run. Hence, the result is different.
The line:
a, b = b, a + b
is closer to:
temp_a = a
a = b
b = temp_a + b
where b is using the old value of a before a was reassigned to the value of b.
Python first evaluates the right-hand expression and stores the results on the stack, then takes those two values and assigns them to a and b. That means that a + b is calculated before a is changed.
See How does swapping of members in the python tuples (a,b)=(b,a) work internally? for the low-down on how this all works, at the bytecode level.
Let's say we start with a and b like this:
a = 2
b = 3
So, when you do:
a, b = b, a + b
what happens is you create the tuple (b, a + b) or (3, 5) and then unpack it into a and b so a becomes 3 and b becomes 5.
In your second example:
a = b
# a is now 3
b = a + b
# b is 3 + 3, or 6.
Let's grok it.
a, b = b, a + b
It's a tuple assignment, means (a, b) = (b, a + b), just like (a, b) = (b, a)
Start from a quick example:
a, b = 0, 1
#equivalent to
(a, b) = (0, 1)
#implement as
a = 0
b = 1
When comes to (a, b) = (b, a + b)
EAFP, have a try directly
a, b = 0, 1
a = b #a=b=1
b = a + b #b=1+1
#output
In [87]: a
Out[87]: 1
In [88]: b
Out[88]: 2
However,
In [93]: a, b = b, a+b
In [94]: a
Out[94]: 3
In [95]: b
Out[95]: 5
The result is different from the first try.
Tha's because Python firstly evaluates the right-hand a+b
So it equivalent to:
old_a = a
old_b = b
c = old_a + old_b
a = old_b
b = c
In summary, a, b = b, a+b means,
a exchanges to get old_value of b,
b exchanges to get the sum of old value a and old value b,
a, b = b, a + b is similar to a, b = 0, 1 assigning values to both variables a, b at same time. First assign a = b and then b = a + b.
I hope that you haven't been influenced by C language, which the priority of assignment operator = is higher than that of Comma operator ,. Do not think it's (a), (b = b), (a + b). It's a tuple assignment, meaning it's (a, b) = (b, a + b).
There are differences between a,b = b,a+b and a=b b=a+b
let's have a look at the following two examples:
eg1:
a,b = 0,1
while a<10:
print(a)
a,b = b,a+b
#output:
0
1
1
2
3
5
8
eg2:
a,b = 0,1
while a<10:
print(a)
a=b
b=a+b
#output:
0
1
2
4
8
This is because the interpreter always calculates the figures in the right side of the Equals sign first. The calculation results will be assigned to the variables which on the left hand side only if all the calculation has been done on the right hand side.

Python (Fibo series): trying to understand what is the difference between a, b = b, a + b OR a = b & a = a + b

I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly.
I am new to python programming. I have this simple code to generate Fibonacci series.
1: def fibo(n):
2: a = 0
3: b = 1
4: for x in range(n):
5: print (a, end=' ')
6: #a, b = b, a+b
7: a = b
8: b = a+b
9: print()
10: num = int(input("enter n value: "))
11: print(fibo(num))
If I execute the above code as-is the result I get is as follows
enter n value: 10
0 1 2 4 8 16 32 64 128 256
If uncomment #6 and comment lines #7 and #8 the result I get is the actual fibo series.
enter n value: 10
0 1 1 2 3 5 8 13 21 34
I would like to know what is the difference between
a, b = b, a + b
and
a = b
b = a + b
Programming IDE used: PyCharm Community 2017.3
a = b
b = a + b
is actually:
a = b
b = b + b
what you want is:
a = b
b = old_value_of_a + b
When you do
a, b = b, a + b
it really is doing:
tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b
which is what you want
In line 7, you've already assigned the value in b to a, so in line 8, new value for b is actually double the old b's value.
While in line 6, the values on the right side of = will be using the old values, that's why you could get Fibo series.
Assignment Statements assigns reference of source variable to target variable. Let walk through an example to understand more
>>> a = 5
>>> b = 6
>>> a = b
In this example b is source variable and a is the target variable. Now memory address for both of these variables are same. We can confirm this as well
>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x1002739e0')
Another test to confirm this is to use is operator
>>> a is b
>>> True
Now coming back to your example. First statement
>>> a, b = b, a + b
Assignes b to a and (a+b) to b. This happens as a single operation so both variables are different. We can apply above tests to confirm this
>>> a is b
>>> False
>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x2008739t0')
The second statement
>>> a = b
>>> b = a + b
Assignes b to a and then (a+b) to b. These are two different statements, so at first step a and b are already identical. Thus the second statement is equivalent to b = b + b.
Thought make it simple so anyone can understand it
if you use this kind of syntax
a = 10
b = 20
a = b
b = a+b
print (a)
print (b)
after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20
so the result will be like
a=20
b=40
but if we use
a = 10
b = 20
a,b = b,a+b
print (a)
print (b)
this will be assigning the values in a single line so the values of a and b will be exactly used from what it is initialised above it and the result will be like
which is the correct solution
a=20
b=30
I think the # line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value temp before, then you can change the values

How to add iteration numbers

my question is about adding loops in python
I am trying to add iteration numbers like summation of all iteration results
For example
first iteration
a = 10
b = 5
a = a + b = 15
c = a = 15
second iteration
a = 15
b = 5
a = a + b = 20
c = a1 + a2 = 35
I know to iterate using for loop which is like this
for i in range(2)
a = 10
b = 5
a = a + b
which gives a = 20
but how to get c which is adding iteration results
a=10
b=5
c=0
for i in range(2):
a = a + b
c = c + a
print a
print c
Above one gives results of a and c
You can define your variable outside your for loop to update it with the sum of each iteration
a_values = [10, 15]
b_values = [5, 5]
c = 0
for a, b in zip(a_values, b_values):
c += a + b
print(c)
35
I am afraid you are quite confused OP. Why don't you just do this instead:
a = 10
b = 5
c = sum(a+b for _ in range(2))
The problem with your version is that after calculating a during the first iteration, you re-assign its value to 10 in the second. Your loop would work with some modifications:
a = 10
b = 5
c = 0
for i in range(2)
c += a + b
You actually don't need any loop if you apply some basic arithmetic:
print(a + n * b)
print(a * n + (n*(n+1))//2 * b)
With a = 10, b = 5 and n = 2, it outputs:
20
35

In line variables in Python 3

Can someone explain the difference between:
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
and
a, b = 0, 1
while b < 10:
print(b)
a = b
b = a+b
Simultaneous:
a = 1
b = 3
a, b = b, a+b
# a: 3; b: 1+3
Sequential:
a = 1
b = 3
a = b
# a: 3; b: 3
b = a+b
# a: 3; b: 3+3
The first one computes all the new values before updating a and b. The second one computes and updates a before computing and updating b. The second one will give incorrect results because of that.
Here's part of a good talk by Raymond Hettinger where he talks about updating multiple state variables at once.
It's a shorthand to avoid a temporary variable. In many traditional languages, you had to do
tmp = a
a = b
b = b + tmp

Python Assignment Order [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 6 years ago.
I am new to python. Can someone explain why the following two python example does not output the same thing?
Example 1
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
Example 2
a, b = 0, 1
while b < 50:
print(b)
a = b
b = a + b
Thanks
In the first version, when you write
a, b = b, a + b
the expression
b, a + b
is evaluated first. After it has been evaluated, it is subsequently assigned to a, b with tuple unpacking. The key point is that the entire right hand side of an assignment statement is evaluated in its entirety before performing the binding of the left-hand side names.
In the second version,
a = b
# a is now re-bound and potentially has changed value
is performed first, and then
b = a + b
# the expression a + b uses the modified value of a
happens after. By which point, a has been re-bound.
So, to illustrate with some values. The first time round the loop, after a, b = 0, 1 we have
# a == 0
# b == 1
a, b = b, a + b
Now, b, a + b is 1, 1. And so we have
a, b = 1, 1
But the alternative goes like this:
a = b
# same as a = 1
b = a + b
# same as b = 1 + 1
You ask in a comment:
How would Example 1 be rewritten into 2 statements?
The safest way is to introduce temporary variables. Like this:
a1 = b
b1 = a + b
# now we can assign to a and b
a = a1
b = b1
In this case you don't actually need two temporary variables, one will suffice, but this is the most general form.
This tuple unpacking is how you swap two values idiomatically in Python. In other languages you write:
temp = a
a = b
b = temp
In Python you write:
a, b = b, a

Categories

Resources