-1

I've tried to understand the logic and process that causes this, but still don't understand why it's happening. Sorry if it's a really simple/bad question.

This is the question:

Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.

This is the code with error:

def sum67(nums):
  ans = 0


  if len(nums) == 0:
    return 0 


  elif 6 not in nums:
    for val in nums:
      ans += val
    return ans  

  elif 6 in nums:
    x = nums.index(6)
    y = nums.index(7, x)
    for i in range(x, y):
      nums.pop(i)

  for val in nums:
    ans += val

  return ans

This is the error:

pop index out of range
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Edward Roy
  • 43
  • 5
  • 3
    You are popping/removing elements from the list while iterating which will cause an error eventually since the indices you expected from the beginning are not valid anymore from 2nd+ iteration. – NewPythonUser Jun 03 '20 at 12:14
  • 2
    We love that you're here and we need code we can debug for you. The screen snip you provided can't be executed. – nicomp Jun 03 '20 at 12:15
  • 1
    For future reference, your question was most likely closed because you posted the code as an image instead of text. – Ahmet Jun 03 '20 at 12:18
  • 1
    Sorry about that – Edward Roy Jun 04 '20 at 00:00
  • Try printing `i` and `nums` right before you `pop`, and you'll see that the original range won't match the element indices anymore. See [python : list index out of range error](https://stackoverflow.com/q/1798796/2745495). – Gino Mempin Jun 04 '20 at 00:21
  • 2
    Learning [how to use a debugger](https://idownvotedbecau.se/nodebugging/) will help you with this and with many other problems. – Dour High Arch Jun 04 '20 at 01:09
  • 1
    Thank you so much guys! I've learnt a lot already, from debuggers, to the solution to my problem, and even how to post correctly. Happy to be here :) – Edward Roy Jun 04 '20 at 04:14

1 Answers1

0

Woohoo! I just learnt about the del function.

My solution was to replace:

elif 6 in nums:
  x = nums.index(6)
  y = nums.index(7, x)
  for i in range(x, y):
    nums.pop(i)` 

with:

while 6 in nums:
  x = nums.index(6)
  y = nums.index(7, x)
  del nums[x:y+1]
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Edward Roy
  • 43
  • 5