Aloizio Macedo
Aloizio Macedo

Reputation: 134

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.

Upvotes: 2

Views: 84

Answers (2)

Gelineau
Gelineau

Reputation: 2090

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)

Upvotes: 0

lejlot
lejlot

Reputation: 66775

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.

Upvotes: 3

Related Questions