def evalPolynomial(coeffs,x):
return sum([n for n in coeffs] * [x**(m-1)for m in range(len(coeffs),0,-1)])
TypeError: can't multiply sequence by non-int of type 'list'
Not sure what's causing the error? When I print each of the statements separately, they each give me a list, but when I try to multiply them it doesn't work.
Python list
s can only be multiplied by an integer, in which case the elements of the list
are repeated:
>>> [1,2,3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
If you want vectorial operations use numpy.ndarray
instead:
>>> import numpy as np
>>> ar = np.array([1,2,3])
>>> ar * 3
array([3, 6, 9])
In particular there is a numpy function for convolution(i.e. polynomial multiplication):
>>> a = np.array([1,2,3]) # 1 + 2x + 3x^2
>>> b = np.array([4,5,6]) # 4 + 5x + 6x^2
>>> np.convolve(a, b) # (1 + 2x + 3x^2) * (4 + 5x + 6x^2)
array([ 4, 13, 28, 27, 18]) # 4 + 13x + 28x^2 + 27x^3 + 18x^4
If you want to evaluate a polynomial there is the numpy.polyval
function which does this.
Keep in mind that using numpy limits the size of the integers, so you might obtain wrong results if the coefficients are so big that they overflow.
The expression [n for n in coeffs]
is a list
, of integers.
Lists do support multiplication by an integer, but this means "make a list that
is n copies of the starting list"; this is not what you want in this mathematical context.
I would recommend that you look at the numpy
(or scipy
which is largely a superset of numpy
) package to help with this. It has a function polyval
for evaluating exactly what you want, and also provides a class based representation polynomial
. In general, for doing numeric computation in Python, you should look at these packages.
But if you want to roll your own, you'll need to do the math inside of the list comprehension, one way to do it is:
return sum( [ n*x**(i-1) for (n,i) in zip( coeffs, xrange(len(coeffs),0,-1)) ] )
You are trying to multiple two lists together. This is not a valid operation in python.
If you want to multiply each corresponding element in the two lists you can use something like this:
def evalPolynomial(coeffs,x):
return sum(x * y for x, y in zip(coeffs, (x**(m-1)for m in range(len(coeffs),0,-1))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With