Philip Adams
Philip Adams

Reputation: 13

How to stop iterating over a list once a certain value is reached

For this problem, a list of integers is given. I need to find the average of the list. The only problem is, once you reach a negative number, you aren't supposed to factor in any of the numbers after that into the calculations. This is what I have so far:

def average_rainfall(listInts):
    newList = []
    count = 0
    for num in listInts:
        if num < 0:
            newList.append(listInts[:num])
            count += (1*len(newList))
        else:
            newList.append(listInts)
            count += (1*len(newList))

    summ = sum(newList)
    avg = summ/count

    return avg   

The list and function call are below:

a_list = [1, 2, 3, 4, 5, -1, 6, 7]
print(average_rainfall(a_list))

I've been working on this for a while and am stuck. Any tips?

Upvotes: 0

Views: 1885

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You could use itertools.takewhile (doc):

from itertools import takewhile

a_list = [1, 2, 3, 4, 5, -1, 6, 7]

def average_rainfall(listInts):
    l = [*takewhile(lambda k: k >=0, listInts)]
    return sum(l) / len(l)

print(average_rainfall(a_list))

Prints:

3.0

Upvotes: 2

Dallan
Dallan

Reputation: 516

Use break inside inside the if block to exit the loop early.

Something like

def average_rainfall(listInts):
    newList = []
    count = 0
    for num in listInts:
        if num < 0:
            newList.append(num)
            count += 1
            break
        else:
            newList.append(num)
            count += 1

    summ = sum(newList)
    avg = summ/count

    return avg   

Edit: There is a bug in your append statements. You need to append the num you are currently iterating on, not the whole list.

Upvotes: 1

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

This is a classic use case for continue or break. To determine which one that you want you have to decide whether or not you want to skip over negative numbers or stop execution entirely.

continue skips one iteration of the loop while break stops execution of the loop entirely.

Upvotes: 0

Related Questions