Birgit Dulanto Birgit Dulanto - 20 days ago 7
Python Question

why doesn't this stop running?

why is this code running like forever? I want it to stop when all numbers in y_list are near to an integer as I defined in "def C(y)"

y_list=[1.0, 3.4 ]
k=1

def C(y):
return abs(y-round(y)) < 0.15

while not all(C(y) for y in y_list):
z_list = [y*k for y in y_list]
k+=1
print(z_list)



Answer

You aren't changing y_list (and you don't want to change it!). And because you're testing the static y_list in the while loop condition, that loop will never end. But you are changing z_list so you need to test that z_list meets your condition.

And so that the while test doesn't fail on the first loop you need to make z_list a copy of y_list before the loop starts.

y_list = [1.0, 3.4 ]

# Copy the original data
z_list = y_list[:]

def C(y):
    return abs(y-round(y)) < 0.15

k = 1
while not all(C(y) for y in z_list):
    z_list = [y*k for y in y_list]
    k+=1
    print(z_list)

output

[1.0, 3.4]
[2.0, 6.8]
[3.0, 10.2]
[4.0, 13.6]
[5.0, 17.0]

Note that I made z_list a copy of y_list by doing

z_list = y_list[:]

If I just did

z_list = y_list

then z_list would simply be another name for the same list object as y_list, you wouldn't get two separate lists.


FWIW, here's another way to write this. We use itertools.count so we don't have to update k manually, and map to call the testing function, which I've given a more meaningful name.

from itertools import count

y_list = [1.0, 3.4 ]
z_list = y_list[:]

def almost_int(y):
    return abs(y - round(y)) < 0.15

for k in count(2):
    print(z_list)
    if all(map(almost_int, z_list)):
        break
    z_list = [y*k for y in y_list]