Search code examples
pythonfor-loopenumerate

Return the sum of elements in an array while ignoring all elements that lie in between elements 6 and 9 (also included)


This is the whole question:

Return the sum of the numbers in the array, except ignore 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.

Examples of what the output should look like are:

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

I have tried to use my own method even though there are other solutions available but I wanted to know why my solution was giving an error. I have tried to initialize a separate list called arr1 and I intend to iterate through the given array until it reaches the first 6. Then I want to keep adding the elements after that 6 into the new array arr1 until the iterator reaches a 9. And as for the rest of the numbers I sum them up in the else block of the code.

Here's my solution:

def summer_69(arr):
    sum = 0
    arr1 =[]
    for x,i in enumerate(arr):
        if i == 6:
            while arr[x]!=9:
                arr1 = i
                x+=1
        else:
            sum += arr[i]
    return sum

I get the following error:

IndexError: list index out of range

Can anyone point out why it's giving me that error?


Solution

  • An iterator solution (I love those):

    def summer_69(arr):
        it = iter(arr)
        return sum(x for x in it if x != 6 or 9 not in it)
    

    This mainly sums the values. And whenever 6 is encountered, the 9 not in it consumes all values until the next 9 (and it's false, so none of the values from that 6 to that 9 make it into the sum).