【发布时间】:2017-08-08 11:35:25
【问题描述】:
下面是我用于 no_teen_sum 和后续的 fixed_teen 函数的代码。
第一个代码是我提交的 - 并且适用于所有测试用例:
def no_teen_sum(a, b, c):
# checks if value is a teen then child conditional checks whether
# fix_teen passes the value, otherwise initialize the value as 0
if 13 <= a <= 19:
if fix_teen(a):
a = a
else:
a = 0
if 13 <= b <= 19:
if fix_teen(b):
b = b
else:
b = 0
if 13 <= c <= 19:
if fix_teen(c):
c = c
else:
c = 0
return a + b + c
以及被调用的 fix_teen 函数:
def fix_teen(n):
# checks if n is 15 or 16 but checking if it is found in the set
# written this way to be expandable without becoming verbose
if n in {15, 16}:
return True
但是,看着这个,我看到了很多重复,并意识到我可能误读了问题的内容。它在寻找解决方案方面是有效的,但不是尽可能干净。所以我尝试着改进。
改进的代码:
def no_teen_sum(a, b, c):
fix_teen(a)
fix_teen(b)
fix_teen(c)
return a + b + c
以及修改后的 fix_teen 函数:
def fix_teen(n):
# checks if n is a teen
if 13 <= n <= 19:
# checks if n is 15 or 16 but checking if it is found in the set
# if True then leave n as it is
if n in {15, 16}:
n = n
return n
# if it fails then n = 0
else:
n = 0
return n
# if n is not in the teens return it as is
return n
我遇到的问题,例如 (1, 2, 18) 的测试用例,它返回 21。它应该返回 3。我尝试在主函数中的每个“fix_teen”调用之间放置打印语句以查看它对 a、b、c 有什么价值,它只是让它们保持原样 (1, 2, 18) 而不是 (1, 2, 0)
奇怪的是,如果我单独调用 fixed_teen(18),它会返回 0。
【问题讨论】:
-
检查你的 no_teen_sum(a, b, c) 函数你正在返回 a + b + c (这就是传递给函数的字面意思)!你应该做 a = fix_teen(a), b = fix_teen(b), c = fix_teen(c) 然后返回 a + b + c
-
噢!现在很有意义。我正在返回该值,但在 no_teen_sum 函数的任何地方都没有收到它。谢谢你。如果您想要解决问题的要点,您可以回答问题,我会给您。
标签: python python-3.x return