Marc43
Marc43

Reputation: 491

How to 'translate' a mathematical expression in python 2.7

I tried to 'translate' (i mean to a language that python can understand) '2x^2+3', i want to get '2*x^2 + 3 (so python can understand it).

eq = '2x^2+3'

newlist = []

if '^' in eq:
   eq = eq.replace('^', '**')
else:
   print ''

for x in range (len(eq)):
    newlist.append(eq [x])

print newlist

And doing that i obtained ['2', 'x', ' * ', ' * ', '2', '+', '3'], but all i want it's to finally obtain '2*x**2 + 3' so Python can understand it.

Upvotes: 0

Views: 1344

Answers (2)

joel goldstick
joel goldstick

Reputation: 4493

Your result is a list of strings which can be joined like so:

expression = "".join(my_list)

But you didn't pick up the part where you want 2x to become 2 * x. I'll leave that part for you to figure out

Upvotes: 1

architectpianist
architectpianist

Reputation: 2552

You can use a technique called infix-postfix conversion to convert the string into an expression that can be evaluated. I used this technique in Objective-C to create a graphing calculator app on iOS, for instance. I'll say up front that it was difficult to support all the different mathematical shorthands that people use--e.g. 2(x + 3) or 2^-2-- but it is possible.

Essentially you process the string and build an infix, which is an array of sequential elements in the expression. Then you convert it to a postfix, which changes the order of the elements to allow easy evaluation. Here is a website that demos infix-postfix conversion.

Here is a gist showing a postfix calculator implementation in Python, but I haven't tried it. Hopefully it gives you an idea of what the process is like.

Upvotes: 0

Related Questions