为什么这个解决方案是错误的?

2024-05-20 05:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理以下codingbat问题:

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

我完全知道这不是最好的解决办法,但我只是想知道为什么这是错的。你能解释一下为什么这是错误的,在哪种情况下它会给出错误的结果吗?


Tags: andoftheinforreturnif错误
3条回答

这是我解决那个问题的办法。正如已经回答过的,问题是6在7之后立即出现。我用稍微不同的方法解决了这个问题,所以我想我会把它贴出来。

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

你的程序有个错误。检查以下结果:

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

这将打印:

8
3
16 <-- wrong

如果7后面紧接着是6,那么您将添加6和以下所有数字。我不确定是否不止一个范围是6。。。输入中允许7,但如果允许,则必须修正算法。

这个简单的实现确实返回了正确的数字:

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

此外,如果由于某些不清楚的原因不需要使用索引,则可以直接遍历列表的元素(for element in list: ...)。

以下是我的解决方案供您参考:

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

相关问题 更多 >