gpt4 book ai didi

python 3 : Use n*x**k to evaluate a list (general_poly)

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

I am trying to answer the same exam question as this OP而且,尽管这些帖子是相关的,但请求的帮助是不同的。

我将讨论我的测试用例以及为什么我认为它必须是一个语义错误,但首先......

考试题:

Write a function called general_poly, that would, for example, evaluate >general_poly([1, 2, 3, 4])(10) to 1234 because *1*10^3 + 2*10^2 + 3*10^1 + >4*10^0*.

So in the example the function only takes one argument with general_poly([1, 2, 3, 4]) and it returns a function that you can apply to a value, in this case x = 10 with general_poly([1, 2, 3, 4])(10).

我的代码:

def general_poly(L):
def in_poly(x):
total = 0
for i in range(0, len(L)):
k = (len(L)-1) - i
total += (L[i] * (x**k))
return total
return in_poly(x)

我们没有被告知具体的错误是什么,也没有给出用于测试代码的列表,只有通过/失败(抛出的错误)以及每个问题的正确答案六项测试。

但是,我们得到了提示,因为第一个问题的答案是 1234,这就是给出的示例。

我知道我至少应该做对那个,但是代码没有通过所有六项测试。

这些是我运行的一些测试用例 - 并用计算器验证了结果 - 所以我认为计算没有错:general_poly:

  • ([1,2,3,4,1,2,3,4])(10) = 12341234;
  • ([1,2,3,4])(0) = 4;
  • ([1,2,3,4])(-7) = -262;
  • ([5,6,7,8,9])(28) = 3210713;
  • ([103, 42, -78, -3.26])(9) = 77783.74

我还检查了缩进,检查了是否有输出,逐行运行它,检查了拼写等,但没有运气。

这可能与我无法将函数调用为 general_poly(L)(x) 有关。我必须在调用函数之前单独声明 x,否则我会得到:

TypeError: 'int' object is not callable

最佳答案

返回函数而不调用它

return in_poly

不是

return in_poly(x)

in_poly(x) 是一个整数,不是函数。

关于 python 3 : Use n*x**k to evaluate a list (general_poly),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366631/

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