如果我使用以下代码手动引入参数,它可以工作:
def evaluatePoly(poly, x):
result = 0
for i in range(len(poly)):
result += poly[i] * x ** i
return float(result)
>>> evaluatePoly([1,2,2],2)
13
我想要被引导只引入系数,没有括号,以及我想要评估多项式方程的值。像这样:
poly=(raw_input('Enter a list of coefficients from your polynomial equation: '))
x=int(raw_input('Enter the value where you want to evaluate your polynomial equation: '))
print(evaluatePoly(poly, x))
但是,如果我尝试这样做,Python会给我这个错误:
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
我该怎么做?
由于
答案 0 :(得分:0)
raw_input
将返回一个字符串。您可以将字符串处理为值列表,如下所示:
coeffs = raw_input('Enter a list of coefficients from your polynomial equation: ') # is a String
poly = coeffs.split() # split the string based on whitespace
poly = map(int, poly) # Convert each element to integer using int(...)
如果您想接受花车,请使用float
代替int
,如果您想要用逗号分割,请使用coeffs.split(",")
代替coeffs.split()
。
>>> x=int(raw_input('Enter the value where you want to evaluate your polynomial equation: '))
Enter the value where you want to evaluate your polynomial equation: 2
>>> coeffs = raw_input('Enter a list of coefficients from your polynomial equation: ')
Enter a list of coefficients from your polynomial equation: 3 2 5
>>> poly = coeffs.split()
>>> poly = map(int, poly)
>>> print(evaluatePoly(poly, x))
27.0
>>>
答案 1 :(得分:0)
使用input()
评估您的eval()
列表,从字符串转换为列表。您的评估可以在函数体内。我在这些行中这样做了
def evaluatePoly(poly, x):
result = 0
poly=eval(poly)
for i in range(len(poly)):
result += poly[i] * x ** i
return float(result)
poly=(input('Enter a list of coefficients from your polynomial equation: '))
x=int(input('Enter the value where you want to evaluate your polynomial equation: '))
print(str(evaluatePoly(poly, x)))
我得到了
>>>
Enter a list of coefficients from your polynomial equation: [1,2]
Enter the value where you want to evaluate your polynomial equation: 5
11.0
请注意,使用eval()
可能会对您的计划造成风险。