davidjglynn davidjglynn - 1 month ago 7
Python Question

looking for a more elegant solution to this


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

Answer

If we can just remove the elements that we don't want, then we can use a simple sum. Here is an example:

def sum67(nums):
    nums=nums[:]
    while 6 in nums:
        i=nums.index(6)
        j=nums.index(7,i)
        del nums[i:j+1]
    return sum(nums)

First, we use nums=nums[:] to make a copy. The caller probably isn't expecting nums to 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 index i. del nums[i:j+1] then deletes the elements in the range from i to j, including the element at j.

Comments