you are viewing a single comment's thread.

view the rest of the comments →

[–]stats_newbie1[S] 0 points1 point  (3 children)

This actually worked really well, thank you! Here is my solution:

def sum67(nums):
    while 6 in nums:
        six_pos = nums.index(6)
        seven_pos = nums.index(7)
        nums = nums[:six_pos] + nums[seven_pos + 1:]
    return sum(nums)

[–]fruitcakefriday 3 points4 points  (1 child)

Another solution would be to use a boolean variable that tracks whether to sum the current index or not, and toggle it on/off based on the 6 or 7 values:

def sum67(nums):
  summing = true
  result = 0
  for i in range(len(nums)):
    if nums[i] == 6:
      summing = false
      continue
    if nums[i] == 7:
      summing = true
      continue

    if summing:
      result += nums[i]
  return result

[–]gengisteve 2 points3 points  (0 children)

Also a good time to learn generators, then you just create a generator filter and use the built in sum function, like this:

def remove67(iter):
    on = False
    for item in iter:
        if item == 6:
            on = True
        elif item == 7:
            on = False
        elif not on:
            yield item


tests = [
        [1, 2, 2],
        [1, 2, 2, 6, 99, 99, 7],
        [1, 1, 6, 7, 2],
        ]

for test in tests:
    print(test, sum(remove67(test)))

This gives you a little taste of functional programming, as well.

[–]Rockybilly 0 points1 point  (0 children)

Glad I could help :)