列表中除6和7之间的数字以外的数字的总和

2024-03-29 08:29:37 发布

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

我正在尝试编写一个函数,它接受一个列表并对列表中的所有数字求和,只是它忽略了列表中以列表开始并扩展到7的部分,但在7之后继续求和。这是我的密码:

def sum67(nums):
   i = 0
   sum = 0
   while i < len(nums):
      k = 0
      if nums[i] != 0:
         sum += nums[i]
         i += 1
      if nums[i] == 6:
         for j in range(i + 1, len(nums)):
            if nums[j] != 7:
               k += 1
            if nums[j] == 7:
               k += 2
               i += k

测试用例显示,6和7之前(包括7)的数字被忽略,而其他数字被添加到总和中,7之后的数字也被添加到总和中(正如预期的那样),但是由于某种原因,6之后的第一个7之后的任何7都没有被加和-这不是我想要的,我不知道为什么会发生这种情况。有什么建议吗?你知道吗

测试用例结果:

[1, 2, 2 Expected: 5. My result: 5 (OK)

[1, 2, 2, 6, 99, 99, 7] Expected: 5. My result: 5 (OK)  
[1, 1, 6, 7, 2] Expected: 4 My result: 4 (Chill)    
[1, 6, 2, 2, 7, 1, 6, 99, 99, 7] Expected: 2    My result: 1 (Not chill)    
[1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7] Expected: 2 My result: 1    (Not chill) 
[2, 7, 6, 2, 6, 7, 2, 7] Expected: 18 My result: 9 (Not chill)

`


Tags: 函数列表lenifmynot测试用例ok
3条回答

张贴的代码已完全损坏。 例如,对于没有任何6的列表, ^当到达最后一个元素的nums[i] == 6条件时,{}将超出列表的范围。你知道吗

你需要完全重新考虑循环中的条件。 这里有一种方法是可行的。 如果当前数字是6, 然后跳过,直到你看到一个7,不加和。 否则加到总数上。 在执行这两个操作(跳过数字或相加)中的任何一个之后, 增量i。你知道吗

def sum67(nums):
    i = 0
    total = 0
    while i < len(nums):
        if nums[i] == 6:
            for i in range(i + 1, len(nums)):
                if nums[i] == 7:
                    break
        else:
            total += nums[i]

        i += 1

    return total
def sum67(nums):
    # flag to know if we are summing
    active = True
    tot = 0
    for n in nums:
        # if we hit a 6 -> deactivate summing
        if n == 6:
             active = False
        if active:
             tot += n
        # if we hit a seven -> reactivate summing
        if n == 7 and not active: 
             active = True
    return tot

下面是学习新Python技术的中间替代方法:

import itertools as it


def span_sum(iterable, start=6, end=7):
    """Return the sum of values found between start and end integers."""
    iterable = iter(iterable)
    flag = [True]
    result = []

    while flag:
        result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
        flag = list(it.dropwhile(lambda x: x!=end, iterable))
        iterable = iter(flag)
        next(iterable, [])
    return sum(result)

# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18

原则上,此函数过滤输入,将值收集到满足您的条件的result中,并删除其余值,然后返回总和。您尤其可以观察以下技巧:

相关问题 更多 >