davidjglynn davidjglynn - 1 year ago 70
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
sum += nums[i]
if nums[i] == 7:
dontadd = 0
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 Source

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):
    while 6 in nums:
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download