Limit of callable variables inside a loop - python

A very simplified example:
n=1
a=n
x=1
y=a+1
while (y-x) <10:
n+=1
print(x,y)
print(n,a)
This would go into an endless loop of :
x= 1 y= 2
n= 2 a= 1
x= 1 y= 2
n= 3 a= 1
x= 1 y= 2
n= 4 a= 1
x= 1 y= 2
n= 5 a= 1
x= 1 y= 2
n= 6 a= 1
x= 1 y= 2
n= 7 a= 1
As you can see, n is being updated by the loop and can be called however a is not being updated to the updated n value. I was wondering why this was. Such is the case if y is just n+1.

Operations on int objects (+= here) always create a new integer object, it doesn't mutate the previous value. Therefore, the changes to n won't be reflected in a despite the a = n assignment.
You need to rebind a to n each time you change the value for n:
while (y-x) <10:
n += 1
a = n

Related

How can I reverse the value of the output?

Let's put int 5 as a sample input; in my code its expressed as this:
n = int(input())
for i in range(0, n):
n = n - 1
print(n**2)
I get an output as:
16
9
4
1
0
Instead I want to reverse the result to:
0
1
4
9
16
How do you go about solving this problem?
The following will reverse the output:
n = int(input())
for i in range(0,n):
print(i**2)
It will loop from 0 to your inputted n value, printing it's square at each iteration. This also negates the need for the n = n - 1 line.
Output:
0 ** 2
1 ** 2
.
.
.
n ** 2

Printing Fibonacci Series having 2 similar codes but different outputs. Why?

Resolve CODE 2 to print output as CODE 1 and give the reason why both of the codes have different outputs.
Fibonacci Series
CODE 1
x = 0
y = 1
while x < 10:
print(x)
x, y = y, x + y
output
0
1
1
2
3
5
8
CODE 2
x = 0
y = 1
while x < 10:
print(x)
x = y
y = x + y
Output
0
1
2
4
8
Those are simply not identical.
In the first code block y becomes x+y and in the second code block y becomes 2*y.
Just a quick note the output of the second code block is 0 1 2 4 8 and not what you wrote (this was fixed).

Behavioural difference of if-if-else and if-elif-else in a while loop

I am unable to get my desired output when 'if-if-else' conditioning is used. However, using 'if-elif-else' works just fine. I have tried tracing but do not understand the reason for the difference in outputs. I am unsure why does it break out after just 1 execution for the 'if-if-else' case and why doesn't it perform like when 'if-elif' is used.
Here are the codes: they are exactly the same except 'if' is replaced with 'elif' on line 8
1.if-if-else
x = 1
y = 0
while True:
if (x is not None ) & (y%30!=0):
y+=1
x=5
print("x=",x)
if y%30==0: #line8
print("ENTERED y=",y)
y-=29
else:
break
2.if-elif-else
x = 1
y = 0
while True:
if (x is not None ) & (y%30!=0):
y+=1
x=5
print("x=",x)
elif y%30==0: #line8
print("ENTERED y=",y)
y-=29
else:
break
Here are the outputs:
1.if-if-else
ENTERED y= 0
x= 5
2.if-elif-else
ENTERED y= 0
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
x= 5
ENTERED y= 0
x= 5
x= 5
x= 5
x= 5
...(prints x=5 for another 29-4 =25 times)
ENTERED y= 0
...(loops endlessly)
Of course there's a difference! elif stands for else if.
When having another if after an if the second if will be checked regardless of the result you got from the first if.
When having an else or an else if (the key point is the else) the statement will be checked only if the first if condition turned out to be False.
Please note that when using the if alone in line 8 then the following else is "connected" to that second if, but when using elif all of the elses and ifs are "the same block". So in the second case since always it's either y % 30 == 0 or y % 30 != 0 (and x is not None) it will never reach the break!

python Program is saying 2 numbers are different when they are the same

Thanks for the help in advance.
I compare 2 variables which hold numbers with the operation !=
the program takes input like this
4
1 2 3 4
Then the program should return the highest product exluding a square product. In this case the result should be 12(4x3) not 16(4x4) but it is incorrectly returning 16.
The code is here
def max_pairwise_product():
n = int(input())
a = input().split()
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != integer1:
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
This is because your comparing an int to a str. I have edited your code minimally to fix this issue, but you have better to edit your list input before hand.
def max_pairwise_product():
n = int(input())
a = input().split() #If I were you I would do: a = [int(x) for x in input().split()]
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != int(integer1): #This is were I have changed
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
You compare string vs. integer which is always False:
for integer1 in a: # integer1 is a string
product = int(integer1) * n
if n != integer1: # n is a number
Fix:
def max_pairwise_product():
_ = input() # not used
a = "1 2 3 4".split() # input() removed and fixed input given
a = sorted(set(map(int,a))) # convert all to intergers and sort unique numbers
maxno = 0
for idx,number in enumerate(a):
for number2 in a[idx+1:]:
maxno = max( maxno, number*number2 )
return maxno
print(max_pairwise_product())
Output:
12
The loops are optimized leveraging the fact that they numbers are sorted and unique - thats why the second loop can be shorter - no need to recompute already computed results.
Its good if you get inputs like '1 1 1 1 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6' because it will only compute for '1 2 3 4 5 6' and never compute any paring twice.

Using `for` in `range(x)` loop

Shouldn't both blocks of code print similar results? Why is the range function inside of the inner loop reevaluated each time the inner for statement is reached while the range function in the outerloop is only evaluated once?
x = 4
for j in range(x)
for i in range(x)
print i
x = 2
Results
0
1
2
3
0
1
0
1
0
1
I know the first 4 integers printed ( 0 - 3) are a result of the code
for j in range(x): code but why are the the following also printed?
0
1
0
1
0
1
The code
x = 4
for j in range(x):
print i
x = 5
Prints
0 1 2 3
Additional Info
Python 2.7 in IDLE
I can only explain by walking through the iterations of the loops, so here goes:
x = 4
for j in range(x)
for i in range(x)
print i
x = 2
First time through.
x = 4
for j in [0, 1, 2, 3]
for i in range [0, 1, 2, 3]
print i
x = 2
prints
0
1
2
3
Now x is set as 2, but the outer loops range has already been executed, so it is not reevaluated.
Code now becomes:
for j in [0, 1, 2, 3]:
for i in [0, 1]:
print i
x = 2
prints
0
1
And this continues two more times.
Function range(x) produces a list of [0,1,2,3,4]. In for loop you iterate over this list.
Your code is equivalent to:
for j in [0,1,2,3]:
for i in [0,1,2,3]:
print i
for i in [0,1]:
print i
for i in [0,1]:
print i
for i in [0,1]:
print i
range(x) is evaluated only once i.e. when the loop begins, that is why modifying x inside the loop has no effect.
However, in the first code clock, you change x to 2 in the inner, so the next time the inner loop is executed, range only gives (0,1).
Edit: your first block of code is equivalent to
x = 5
for i in range(x)
print i
x = 2
Here is how I view it:
Inner loop is executed for each iteration of outer loop
x = 4
j = 0
for i in range (x):
print(i)
x = 2
j = 1
for i in range(x) # this x is no longer 4 but it is 2
print(i)
x = 2
j = 2
for i in range (x): # this x is, of course, 2
print(i)
x = 2
j = 3
for i in range (x): # this x is, of course, 2
print(i)
x = 2
j is not printed, insert " print('xx', j, 'oo') " before " for i in range(x): "
then change to "print('xx', x, 'oo')
or change 'for j in range(x):' to 'for j in range(225,200,-5):' follow with 'print(j)' before 'for i in range(x):'

Categories