AApro
AApro

Reputation: 43

Create polynomial with given coefficients

I want to create a polynomial with given coefficients in Python but without numpy or any similar library.

For example, if input is (12,2,5,3) which is a0,a1,a2,a3 respectively, expected output is 12+2x+5x^2+3x^3.

def polynomial(p,x):
    return sum((a*x**i for i,a in enumerate(p)))

polynomial(([12,2,5,3]),x)

I tried the code above but I got an error message, naturally, that x is not defined. What is wrong with the code or is there a problem with running it?

Upvotes: 0

Views: 3335

Answers (3)

Tarifazo
Tarifazo

Reputation: 4343

You can take advantage of map:

def polynomial(p, x):
  return sum(map(lambda (i, c): c * pow(x, i), enumerate(p)))

Upvotes: 0

rassar
rassar

Reputation: 5660

The x is not defined error is not from your function, but where you call the function. You need to call the function with an actual number:

poly = polynomial([12, 2, 5, 3], 5)

Also, you may want to consider making poly a function that returns a function; namely, so that you could use the syntax:

poly = polynomial([12, 2, 5, 3])
poly(5) # poly evaluated at 5
poly(10) # poly evaluated at 10

To do that, use this syntax:

def polynomial(p):
    return lambda x: sum(a*x**i for i, a in enumerate(p))

Upvotes: 1

JVL
JVL

Reputation: 77

I don't know if it's what you're looking for, but you can use sympy for symbolic language, something like this:

from sympy import symbols

def polynomial(coefs,var):
    x = symbols(var)
    return [c*x for c in coefs]

>> polynomial([1,2,3,4],'x')
[x, 2*x, 3*x, 4*x]

If it does not solve your problem, it can give you an idea of how to solve it.

Regards

Upvotes: 0

Related Questions