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
inwould work here, it is incorrect, since a sequence4,6,0,9,7will be11... - willeM_ Van Onsemnumis a tuple and you are checking if it is inside a list of ints, so the first condition is met and thesumis returned - Tomerikoo