以下是我用于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.
答案 0 :(得分:4)
你的no_teen_sum(a,b,c)函数返回一个+ 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
答案 1 :(得分:0)
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)
答案 2 :(得分:-1)
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