share
Stack OverflowMy question is about a code i have described but it didn't work
[-3] [2] Vestige Guruji
[2019-08-04 15:09:15]
[ python pycharm ]
[ https://stackoverflow.com/questions/57347717/my-question-is-about-a-code-i-have-described-but-it-didnt-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.

Even if the in would work here, it is incorrect, since a sequence 4,6,0,9,7 will be 11... - willeM_ Van Onsem
Why do you expect the above to work by the way? - willeM_ Van Onsem
num is a tuple and you are checking if it is inside a list of ints, so the first condition is met and the sum is returned - Tomerikoo
(1) Please improve your title to be more descriptive. - EJoshuaS
Lots of things you need to think about in order to do what you want. a) Pop doesn't work the way you have coded it as an answer below states, b) You assuming that a 6 will always be followed by 7, 8, 9, but your question doesn't state that. c) You don't iterate at all. How would you deal with [1,6,1,9,2,6,3,9] - it can't be done without a loop d) Even when you do iterate over a list, it's probably not a great idea to pop numbers out of the list you're iterating over. A safer idea would be to iterate over a new list and append the values that you do want in your answer and skip the others - David Buck
(1) Before anyone else jumps on point c) above - without regex, but I'm assuming that's not in scope... - David Buck
Is it possible to please fix the title. I think at least half of the questions here deal with persons that wrote some code that did not end up producing the expected result. That's not very "descriptive". - willeM_ Van Onsem
[0] [2019-08-04 15:25:24] Abel

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).


1
[0] [2019-08-04 17:20:40] learner-coder

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


2