user506710
user506710

Reputation:

Splitting an expression

I have to split a string into a list of substrings according to the criteria that all the parenthesis strings should be split .

Lets say I have (9+2-(3*(4+2))) then I should get (4+2), (3*6) and (9+2-18).

The basic objective is that I learn which of the inner parenthesis is going to be executed first and then execute it.

Please help....


It would be helpful if you could suggest a method using re module. Just so this is for everyone it is not homework and I understand Polish notation. What I am looking for is using the power of Python and re module to use it in less lines of code.

Thanks a lot....

Upvotes: 2

Views: 231

Answers (4)

kzh
kzh

Reputation: 20598

Try something like this:

import re
a = "(9+2-(3*(4+2)))"
s,r = a,re.compile(r'\([^(]*?\)')
while('(' in s):
    g = r.search(s).group(0)
    s = r.sub(str(eval(g)),s)
    print g
    print s

Upvotes: 1

Ant
Ant

Reputation: 5414

i don't know exactly what you want to do, but if you want to add other operations and if you want to have more control over the expression, i suggest you to use a parser

http://www.dabeaz.com/ply/ <-- ply, for example

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77251

The eval is insecure, so you have to check input string for dangerous things.

>>> import re
>>> e = "(9+2-(3*(4+2)))"
>>> while '(' in e:
...     inner = re.search('(\([^\(\)]+\))', e).group(1)
...     e = re.sub(re.escape(inner), eval('str'+inner), e)
...     print inner,
... 
(4+2) (3*6) (9+2-18)

Upvotes: 4

Andrew White
Andrew White

Reputation: 53496

This sounds very homeworkish so I am going to reply with some good reading that might lead you down the right path. Take a peek at http://en.wikipedia.org/wiki/Polish_notation. It's not exactly what you want but understanding will lead you pretty close to the answer.

Upvotes: 0

Related Questions