我正在处理以下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
我完全知道这不是最好的解决办法,但我只是想知道为什么这是错的。你能解释一下为什么这是错误的,在哪种情况下它会给出错误的结果吗?
这是我解决那个问题的办法。正如已经回答过的,问题是6在7之后立即出现。我用稍微不同的方法解决了这个问题,所以我想我会把它贴出来。
你的程序有个错误。检查以下结果:
这将打印:
如果7后面紧接着是6,那么您将添加6和以下所有数字。我不确定是否不止一个范围是6。。。输入中允许7,但如果允许,则必须修正算法。
这个简单的实现确实返回了正确的数字:
此外,如果由于某些不清楚的原因不需要使用索引,则可以直接遍历列表的元素(
for element in list: ...
)。以下是我的解决方案供您参考:
相关问题 更多 >
编程相关推荐