gpt4 book ai didi

python: codingbat no_teen_sum - 为什么我的函数没有按预期工作?

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:27 28 4
gpt4 key购买 nike

下面是我用于 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 有什么值(value),它只是让它们保持原样 (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

关于python: codingbat no_teen_sum - 为什么我的函数没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42848572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com