Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodingBat sum67: why is this solution wrong?

Tags:

python

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?

like image 533
Wilco Avatar asked Dec 05 '11 12:12

Wilco


3 Answers

Below is my solution for your reference:

def sum67(nums):
flag=False
sum=0

for num in nums:
    if(num==6):                  #Turn the flag on if the number is 6
        flag=True
        continue
    if(num==7 and flag is True): #Turn the flag Off when 7 is seen after 6
        flag=False
        continue
    if(flag is False):           #Keep on adding the nums otherwise
       sum+=num
return sum
like image 66
Anirudh Avatar answered Nov 12 '22 21:11

Anirudh


Well, your program has a bug. Check the results of the following:

print sum67([1,2,5])
print sum67([1,2,6,5,7])
print sum67([1,2,6,5,7,6,7])

This will print:

8
3
16 <-- wrong

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:

def sum67(nums):
    state=0
    s=0
    for n in nums:
        if state == 0:
            if n == 6:
                state=1
            else:
                s+=n
        else:
            if n == 7:
                state=0
    return s

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: ... ).

like image 28
hochl Avatar answered Nov 12 '22 21:11

hochl


Here's my solution to that problem. As answered already, the issue is when a 6 occurs immediately after a 7. I solved this in a slightly different way, so I thought I'd post it.

def sum67(nums):
  total = 0
  i=0  
  while i < len(nums):
    if nums[i] == 6:
      while nums[i] != 7:
        i+=1
      i+=1
    if i<len(nums) and nums[i]!=6:  
      total+=nums[i]
      i+=1
  return total
like image 37
TheNeophyte Avatar answered Nov 12 '22 22:11

TheNeophyte