下面是我用于 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”调用之间放置 print 语句以查看值是什么它有 a、b、c,只是将它们保留为 (1, 2, 18) 而不是 (1, 2, 0)
奇怪的是,如果我独立调用fixed_teen(18),它会返回0。
您的 no_teen_sum(a, b, c) 函数返回 a + b + c (这实际上就是传递给函数的内容)!您应该使 a、b 和 c 等于 fix_teen 函数的结果才能获得所需的结果!
def no_teen_sum(a, b, c):
a = fix_teen(a)
b = fix_teen(b)
c = fix_teen(c)
return a + b + c
def no_teen_sum(a, b, c):
return print(fix_teen(a) + fix_teen(b) + fix_teen(c))
def fix_teen(n):
if n in (13, 14, 17, 18, 19):
return 0
return n
no_teen_sum(1, 2, 3)
no_teen_sum(2, 13, 1)
no_teen_sum(2, 1, 14)
def no_teen_sum(a, b, c):
teens = [13, 14, 17, 18, 19]
nums = [a,b,c]
sum = 0
for num in nums:
if num in teens:
sum += 0
else:
sum += num
return sum
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
def fix_teen(n):
teen = [13, 14, 17, 18, 19]
if n in teen :
return 0
else:
return n