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.
sum67([1, 2, 2]) ? 5 sum67([1, 2, 2, 6, 99, 99, 7]) ? 5 sum67([1, 1, 6, 7, 2]) ? 4
def sum67(nums):
dontadd = 0
sum = 0
for i in range(0, len(nums)):
if dontadd == 0:
if nums[i] == 6:
dontadd = 1
else:
sum += nums[i]
else:
if nums[i] == 7:
dontadd = 0
else:
pass# nothing happens. It is useful as a placeholder when a statement is required syntactically
return sum
Looking for a more elegant solution to this problem from codingbat. This answer doesn’t seem as intuitive as it could be
If we can just remove the elements that we don’t want, then we can use a simple sum. Here is an example:
First, we use
nums=nums[:]to make a copy. The caller probably isn’t expectingnumsto change.nums.index(6)finds the index of the first element that has a value of 6.nums.index(7,i)finds the index of the first element that has a value of 7 after the indexi.del nums[i:j+1]then deletes the elements in the range fromitoj, including the element atj.