How can I stop a loop, this function sort my list as I wish but I want to stop it when it done the task.
I have a list x = [4,4,2] and during 15 attempt I want to sort it like that x = [1,2,3,4], if the function sort it after 8 attempt then I want to stop my loop .
I was wondering if anyone in the community could

def kopi(x):
    y = []
    b = 0
    for num in x:
        new_num = num - 1
        if new_num < 0:
           del new_num
    y.append (b)
    print b
    print "new list inside function", y
    return y

##   15 iterations
if __name__ == "__main__":
   y = []
   print "the beginning list is", x
   for k in range(0, 15):
10 Years
Discussion Span
Last Post by Mackjan

The command you want is 'break'. I'll leave it to you to look up the syntax. There are a couple of ways you can test for what you need. First, lists have a 'sort' method. Use that to tell what the sorted list should look like. Then after each iteration of the loop, compare what you have to the sorted list. When you have a match, you can stop. Another is to compare your list before and after your function call. If they match, your list should be sorted. Again, you can stop.


Deleting new_num from x does nothing useful. You are using num and deleting new_num which may or may not be in x. You want to append to y if num > 0

for num in x:
   if num > 0:     ## eliminate if num-1 <= zero

Why did I do that?
Because I don’t want to append digits which are smaller then zero like -1,-2,… in this way I want to delete them before they appends to my list. I want increase b only when I have a digit bigger then zero and I can subtract one.
I don’t want to use the len(x) because if I have x = [] the len(x) = 6 but I have only 5 digits which I can subtract one, zero is not in count because 0-1 = -1 and -1 < 0 .

About how to stop my loop I have same ideas but don’t know how to implement them, for example if I compare x and y they are similar already from beginning not good idea, but if I put a copy of x in z and before next call of my function I compare x and z may be…. What do you say?


Hi gays
I have done it. When I call my function I wrote x = kopi (x) and before next call of my function I compare kopi(x) with x.

for k in range(0, 25):
        if kopi(x)==x:
            print "det gick bra till slut"

is it a good way to stoop it or not??
Thanks a lot

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.