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,这是给出的示例。
我知道我至少应该正确那一项,但代码未通过所有六项测试。
这些是我运行的一些测试用例 - 并用计算器验证了结果 - 所以我不认为计算错误: 通用聚:
- ([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/