0

I want to use a string of a polynomial in a lambda expression, but I couldn't figure out how to do it. It may not be possible, but if it is I'd love some help!

An example of what I'm trying to do is:

f = lambda x: '3*x^3 + 2*x^2 -4*x +8'

Assume that I only have access to the polynomial in type str.

Is there something that removes the quotes or a version of eval that works with variables?

Micah G
  • 3
  • 2

2 Answers2

1

Instead of a lambda you can use np.polyval from numpy

In [19]: import numpy as np

In [20]: np.polyval([3,2,-4,8],2)
Out[20]: 32

If you meant 4^x then a quick fix

In [21]: np.polyval([3,2,0,-pow(4,2)+8],2)
Out[21]: 24

or with lambda

f=lambda mylist,x: sum((x**power) * coeff for power, coeff in enumerate(reversed(mylist)))

print f([3,2,-4,8],2)
Ajay
  • 5,267
  • 2
  • 23
  • 30
0

Do you want to avoid using eval? Otherwise you can just do:

x = 2
eq = '3*x^3 + 2*x^2 -4^x +8'
eval(eq.replace('x',str(x)).replace('^','**'))

In Python ^ is a bitwise operator, so it needs to be replaced by the ** operator.

Also check out the SymPy package.

tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108
  • 1
    As a one-liner: `f = lambda x: eval('3*x^3 + 2*x^2 -4^x +8'.replace('x', str(x)).replace('^', '**'))` – sobolevn May 24 '15 at 17:48