I’m working on the following codingbat problem:
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
My solution is:
def sum67(nums):
sum = 0
throwaway = 0
for i in range(len(nums)):
if throwaway == 0:
if nums[i] == 6:
throwaway = 1
elif throwaway == 1 and i > 0 and nums[i-1] == 7:
throwaway = 0
if throwaway == 0:
sum += nums[i]
return sum
I totally know this is not the best solution, but I’m just curious to know why this is wrong. Could you please explain me why this is wrong and in which particular case it gives a wrong result?
Well, your program has a bug. Check the results of the following:
This will print:
If a 7 is followed by a 6 immediately, you will add the 6 and all following numbers. I’m not sure if more than one range of 6 … 7 is allowed in the input, but if it is, you have to fix your algorithm.
This simple implementation does return correct numbers:
Besides, if you don’t need to use an index for some obscure reasons, you can directly iterate over the elements of a list (
for element in list: ...).