Skip to content
Advertisement

How to ignore numbers after specific number in the list/array in Python?

I’m stuck on this problem:

I was trying to return sum of list of numbers in the array ignoring sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.

Here are my test cases:

number_69([1, 3, 5]) --> 9
number_69([4, 5, 6, 7, 8, 9]) --> 24
number_69([2, 1, 6, 9, 11]) --> 14

I came up with something like:

def number_69(arr):
   for num in arr:
     if 6 not in arr and 9 not in arr:
        return sum(arr)
     return 0

Advertisement

Answer

i guess we stop adding when we see 6 and we start again when we see 9

def number_69(arr):
    sum = 0
    stop = False
    for num in arr:
        if num == 6:
            stop = True
        elif num == 9:
            stop = False
        elif stop is False:
            sum = sum + num
    return sum

print(number_69([2, 1, 6, 9, 11]))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement