简体   繁体   中英

How to make a loop run up to when it stops making sense?

I have a loop inside a program which should be

while number >= lst[count]:
    rank -= 1
    count += 1

where I would like the while to run until it stops making sense. I've attempted somethings which have not worked (see the end of the post), but the following has worked:

lst = [int(x) for x in input().split()]
number = int(input())
count = 0
rank = 0

def attempt(lst, a):
    try:
        result = lst[a]
    except:
        result = float('inf')
    return result


while number >= attempt(lst, count):
    rank -= 1
    count += 1
print(rank)

However, I don't think this is very elegant and seems contrived. Is there a more elegant solution (for this case, and also in general for a given condition)?


Other attempts (which were unsuccessful):

while aliceScores[i] >= lst[count] and count < len(lst):
    rank -= 1
    count += 1

The above fails because the while tries to run for count = len(lst) and runs an error, since lst[len(lst)] does not exist.

while aliceScores[i] >= lst[count] and count < len(lst)-1:
    rank -= 1
    count += 1

The above fails because I want to modify the rank if the condition happens also in the case lst[len(lst) - 1], which would not be seem in the above code.

The only reason why

while aliceScores[i] >= lst[count] and count < len(lst):
    rank -= 1
    count += 1

does not work is that you cannot evaluate lst[count] when count is too big, however you can exploit the fact python short-circuits and/or operators

while count < len(lst) and aliceScores[i] >= lst[count]:
    rank -= 1
    count += 1

This way the loop will stop properly either if count is too big, or if the second condition becomes False.

Why not use a for to iterate the list, and an enumerate to count the number of tries. It would be more pythonic than a while imho.

def get_rank(...):
   for index, lst_number in enumerate(lst):
       if number < lst_attempt:
           return -index
   return -len(lst)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM