The challenge is from codingbat - Sum the elements of the array except for all values between 6 and 7, not counting the 6 or the 7 either.
My strategy was create a new array "valid" and append valid elements of the array nums to the "valid" array, and then sum the valid array.
Because I need the index to check for a 7 once a 6 is detected, my plan was to enumerate the array, and when the value 6 is found, to loop through the remainder of the array until a 7 is found, not appending the values 6-7 to the array "valid" in the process.
I ran my code through the MIT Python tutor to see where it was going wrong, and when I increment the index after i+1 != 7 (with the intention of checking to see if the next value in the array is a 7) it increments the index (it finishes working with that index of the array and moves on to the next one, rather than sticking in the code for the 6 and continuing to loop through and check for a 7).
Appreciate any help with this, especially a solution that sticks to the original strategy but implements it correctly in the code.
def sum67(nums):
valid = []
for i,c in enumerate(nums):
if c == 6:
#when a 6 comes up
if nums[i+1] == 7:
#if the next number is a 7
i+=1
break
#increment and break
else:
i+=1
#increment
else:
valid.append(c)
return sum(valid)
sum67([1, 2, 2, 6, 99, 99, 7])
Edit 1: The desired output for
sum67([1, 2, 2, 6, 99, 99, 7])
is 5. (Because 1 + 2 + 2 = 5, and the 6, 99, 99, and 7 are excluded because they are or are between a 6 and a 7)