简体   繁体   中英

My question is about a code i have described but it didn't work

SUMMER OF '69: 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.¶

I have tried to use the pop method but it didn't work. I want to know why.

def summer_69(arr):
    num=(6,7,8,9)
    if num not in arr:
        return sum(arr)
    if num in arr:
        arr.pop(num)
        return sum(arr)

print(summer_69([4,5,6,7,8,9]))

I am getting the whole sum like in this one I am getting like 39.

Pop removes the item at a specified index. Max index in your array is 5 (4 has index 0). I recommend finding the index of 6 via

arr.index(6)

Not efficient, but you can then repeatedly pop that index until it becomes 9, (and popping once more if "extending to" means including the 9).

Instead of doing this i will suggest you to use a single loop as it will be more efficient. Use single loop and keep adding number to sum until 6 is encountered. As soon as 6 comes skip the numbers till a 9 occurs. Again start to add numbers to sum. Runs in O(n).

i=0

Sum =0

While i < length:

If a[i] == 6:

     While i < length and a[i] != 9:

         i += 1

Else:

    Sum += a[i]

i += 1

return Sum

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