关于python:需要求和a,b,c,除非它们等于13,14,17,18,19

Need to sum a,b,c, unless they equal 13,14,17,18,19

这是我的任务:

Given 3 int values, a b c, return their sum. 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. Write a separate helper"def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e."decomposition"). Define the helper below and at the same indent level as the main no_teen_sum().

我唯一能想到的解决方案是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
excep = [13,14,17,18,19]

def no_teen_sum(a, b, c):
  if a in excep and b in excep and c in excep:
    return 0
  elif a in excep and b in excep and c not in excep:
    return c
  elif b in excep and c in excep and a not in excep:
    return a
  elif a in excep and c in excep and b not in excep:
    return b
  elif a in excep and b not in excep and c not in excep:
    return b+c
  elif b in excep and a not in excep and c not in excep:
    return a+c
  elif c in excep and a not in excep and b not in excep:
    return a+b
  else:
    return a+b+c


只需分解任务并按照它告诉您的方式实现它。让我们一部分一部分地尝试一下:

Given 3 int values, a b c, return their sum. 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.

你已经理解了这个原则。

Write a separate helper"def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule.

继续写这个函数。您已经知道如何使用if测试"teen"值,以及如何使用return值。

In this way, you avoid repeating the teen code 3 times (i.e."decomposition").

这是告诉您实际调用fix_teen三次,并解释说这很好,因为您不会重复自己=只执行一次。

Define the helper below and at the same indent level as the main no_teen_sum().

现在只需使用fix_teen来实现no_teen_sum。怎样?对这三个输入中的每一个调用它,以调整添加到结果中的值。

实际的实现留给OP作为练习。