简体   繁体   中英

how to add inputs to this piece of code?

If I use the following code introducing the parameters manually, it works:

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

I would like to be asked to introduce only the coefficients, without brackets, and the value where I want to evaluate my polynomial equation. Something like this:

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

But if I try that, Python gives me this error:

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

How can I do it?

Thanks

raw_input will return a string. You can process a string into a list of values like so:

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(...)

If you want to accept floats, use float instead of int , and if you want to split on comma, use coeffs.split(",") instead of coeffs.split() .

example

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

evaluate your input() list with eval() , converting from string to list. Your evaluation can be inside function body. I did so in these lines

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

and i get

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

please note that using eval() may be a risk for your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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