代码通过所有测试但在其他测试中失败..请点击链接

时间:2016-07-24 07:43:57

标签: python

返回数组中数字的总和,忽略6到7之间的数字部分(每6个数字后跟至少一个7)。返回0表示没有数字。

sum67([1, 2, 2]) → 5    
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4

我的代码:

def sum67(nums):
    total = 0
    n = 0
    while(n < len(nums)):
        if nums[n] == 6:
            while(nums[n] != 7 and n < len(nums)):
                n += 1
            n += 1
        if n > len(nums)-1:
            break
        total += nums[n]
        n += 1
    return total

click here to test

3 个答案:

答案 0 :(得分:0)

如果在6之后直接7,就会出现问题。

您的代码会检测到第一个6并向前跳过下一个7。但如果下一个号码是另一个6,则不会被跳过。

如果您将if nums[n]==6:更改为while n<len(nums) and nums[n] == 6:,它就会有效。

答案 1 :(得分:0)

@Rawing正确调试了这个。如果您愿意,这是另一个简单的修复:

def sum67(nums):
    total = 0
    n = 0

    while n < len(nums):
        if nums[n] == 6:
            # Skip forward until we find a 7 (or the end of the list).
            while n < len(nums) and nums[n] != 7:
                n += 1
        else:
            total += nums[n]

        # We're either looking at a number we just added to the total,
        # or we're looking at the 7 we just found. Either way, we need
        # to move forward to the next number.
        n += 1

    return total

答案 2 :(得分:0)

正如@Rawing所指出,您的代码并未涵盖6之后7紧随其后的情况。您可以自己迭代列表上的数字而不是拥有多个循环并更新循环计数器,并且如果您需要跳过它们,还有额外的变量告诉您​​:

def sum67(nums):
    skip = False
    total = 0
    for x in nums:
        if skip:
            if x == 7:
                skip = False
        elif x == 6:
            skip = True
        else:
            total += x

    return total