繁体   English   中英

如何在这段代码中添加输入?

[英]how to add inputs to this piece of code?

如果我使用下面的代码手动介绍参数,那么它将起作用:

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'

我该怎么做?

谢谢

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
>>>

使用eval()评估您的input()列表,从字符串转换为列表。 您的评估可以在功能体内进行。 我是在这些行中这样做的

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()可能会对您的程序造成风险。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM