使用python helper函数从循环中排除数字

Using Python helper function exclude numbers from a loop

给定3个int值,a b c返回它们的和。但是,如果其中任何一个值是青少年(包括13-19),则该值计为0,除了15和16不计为青少年。编写一个单独的助手"def fix teen(n):",它接受一个int值并返回为teen规则固定的值。这样,您就可以避免重复青少年代码3次(即"分解")。

Define the helper below and at the same indent level as the main no_teen_sum().Again, you will have two functions for this problem!

1
2
3
4
def no_teen_sum(a, b, c):
  # CODE GOES HERE
def fix_teen(n):
  # CODE GOES HERE

实例:

1
2
3
4
*no_teen_sum(1, 2, 3)6
*no_teen_sum(2, 13, 1)3
*no_teen_sum(2, 1, 14)3
*no_teen_sum(2, 16, 1)19

我拿到第一部分了

1
2
3
4
5
6
7
8
9
def no_teen_sum(a, b, c):
    total = 0
    for i in (a, b, c):
        if i in range(13, 20):
            x = 0
        else:
            x = 1
        total += i*x
    return total

只是在第二个问题上挣扎


However, if any of the values is a teen -- in the range 13-19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens.

您在当前的解决方案中忘记了1516(并且没有在其中使用第二个函数)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
>>> def no_teen_sum(a, b, c):  # your solution
...     total = 0
...     for i in (a, b, c):
...         if i in range(13, 20):
...             x = 0
...         else:
...             x = 1
...         total += i*x
...     return total
...
>>> no_teen_sum(1, 2, 3) == 6
True
>>> no_teen_sum(2, 13, 1) == 3
True
>>> no_teen_sum(2, 1, 14) == 3
True
>>> no_teen_sum(2, 16, 1) == 19  # 16 doesn't count as 0
False

# Solution
>>> def no_teen_sum(a, b, c):
...     return sum(fix_teen(num) for num in (a, b, c))
...
...
... def fix_teen(n):
...     teens = {13, 14, 17, 18, 19}
...     return 0 if n in teens else n
...
>>> no_teen_sum(1, 2, 3) == 6
True
>>> no_teen_sum(2, 13, 1) == 3
True
>>> no_teen_sum(2, 1, 14) == 3
True
>>> no_teen_sum(2, 16, 1) == 19
True

简化版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def no_teen_sum(a, b, c):
    result = 0
    for num in (a, b, c):
        result += fix_teen(num)
    return result


def fix_teen(n):
    if n in {13, 14, 17, 18, 19}:
        return 0
    else:
        return n


if __name__ == '__main__':
    assert no_teen_sum(1, 2, 3) == 6
    assert no_teen_sum(2, 13, 1) == 3
    assert no_teen_sum(2, 1, 14) == 3
    assert no_teen_sum(2, 16, 1) == 19