python:codingbat no_teen_sum-为什么我的函数不是';你没按预期工作吗?
下面是我用于no_teen_sum和后续fixed_teen函数的代码 第一个代码是我提交的,并且适用于所有测试用例:python:codingbat no_teen_sum-为什么我的函数不是';你没按预期工作吗?,python,python-3.x,return,Python,Python 3.x,Return,下面是我用于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:
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
然而,看到这一点,我看到了很多重复,并意识到可能我误解了问题的内容。就找到解决方案而言,这是有效的,但并没有尽可能干净。所以我试着改进
改进代码:
def no_teen_sum(a, b, c):
fix_teen(a)
fix_teen(b)
fix_teen(c)
return a + b + c
以及修改后的fix_函数:
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
def fix_teen(n):
#检查n是否是青少年
如果13您的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
检查你的no_teen_sum(a,b,c)函数你返回的是a+b+c(这是传递给函数的字面意思)!你应该先做a=fix\u teen(a),b=fix\u teen(b),c=fix\u teen(c),然后返回a+b+cDoh!现在说得通了。我正在返回值,但在no_teen_sum函数的任何地方都没有得到它。非常感谢。如果你想要解决问题的分数,你可以回答这个问题,我会给你的。欢迎来到StackOverflow。虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。你也应该用代码围栏对你的代码进行分类。虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高你的文章质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请您的回答添加解释,并说明适用的限制和假设。返回打印结果意味着您总是返回None
。
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 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
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)