0

如果我使用以下代码手动引入参数,它可以工作:

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'

我该怎么做?

谢谢

4

2 回答 2

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
>>>
于 2013-05-19T16:48:38.913 回答
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()可能会给您的程序带来风险。

于 2013-05-19T16:59:19.087 回答