I have a specific programing task
给定3个int值,a b c返回它们的和。但是,如果其中任何一个值是青少年(包括13到19),则该值计为0,但15和16不计为青少年。编写一个单独的助手"def fix teen(n):",它接受一个int值并返回为teen规则固定的值。这样,您就可以避免重复青少年代码3次(即"分解")。在下面和与main no tene_sum()相同的缩进级别定义助手。
我的解决方案:
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 | def no_teen_sum(a,b,c): sum=0 lst=[13,14,15,16,17,18,19] def fix_teen(n): s=0 if n >=13 and n<= 19: if n==15: s=15 elif n==16: s=16 else: s=0 return s if (a not in lst) and (b not in lst) and (c not in lst): sum=a+b+c elif a in lst : sum=fix_teen(a)+b+c if b in lst: sum=fix_teen(a)+fix_teen(b)+c elif b in lst: sum=a+fix_teen(b)+c if c in lst: sum=a+fix_teen(b)+fix_teen(c) elif c in lst: sum=a+b+fix_teen(c) if a in lst: sum=fix_teen(a)+b+fix_teen(c) else: sum=fix_teen(a)+fix_teen(b)+fix_teen(c) return sum |
输出:
1 2 3 4 5 6 7 8 9 | >>> no_teen_sum(14,1,13) 14 # the answer should be 1 >>> no_teen_sum(14,2,17) 19 # the answer should be 2 >>> no_teen_sum(16,17,18) 34 # the answer should be 16 >>> no_teen_sum(17,18,19) 19 # the answer should be 0 |
任何建议都将非常感谢。事先谢谢……
问题是你是怎么写的"修复青少年"的。您只需将号码发送给Fix Teen,并按如下方式书写:
1 2 3 4 5 | def fix_teen(n): if (n >= 13 and n <=19): if (n!= 15 and n != 16): n = 0 return n |
那么,你的常规方法可以是:
1 2 | def no_teen_sum(a,b,c): return fix_teen(a) + fix_teen(b) + fix_teen(c) |
这将缩短代码并修复错误。
你使事情变得超复杂:你不应该写所有那些
如果一个数字在13到19之间,而不是15或16,那么这个数字就算作青少年。所以我们可以写:
1 2 3 4 | def fix_teen(n): if n >= 13 and n <= 19 and (n < 15 or n > 16): return 0 return n |
或者更优雅:
1 2 3 4 | def fix_teen(n): if 13 <= n <= 19 and not (15 <= n <= 16): return 0 return n |
接下来我们可以简单地写:
1 2 | def no_teen_sum(a,b,c): return sum(fix_teen(n) for n in (a,b,c)) |
我们也可以很容易地用
1 2 | def no_teen_sum(*args): return sum(fix_teen(n) for n in args) |
现在我们可以用任意数量的值来调用它。这将导致:
1 2 3 4 5 6 7 8 | >>> no_teen_sum(14,1,13) 1 >>> no_teen_sum(14,2,17) 2 >>> no_teen_sum(16,17,18) 16 >>> no_teen_sum(17,18,19) 0 |
列表理解的简单方法:
1 2 3 | def no_teen_sum(*args): # *args means that it can take any number of arguments and pass it as a tuple to the function no_teens = [n for n in args if any([n in (15, 16), n not in range(13, 20)])] # List comprehension that will iterate the passed arguments and omit anything between 13-19 except 15 & 16 return sum(no_teens) # return the sum |
编辑:在再次阅读您的问题后,我注意到您需要一个
1 2 3 4 5 6 | def no_teen_sum(a, b, c): no_teens = [teen_fix(n) for n in [a, b, c]] return sum(no_teens) def teen_fix(n): return n if any([n in (15, 16), n not in range(13, 20)]) else 0 |