1

The problem I'm facing is being able to take an string like "((1+4)) + (2-1) - 3" and turn it in a list with [((1+4)), (2-1), 3] in it. This would also apply to other amount of parentheses. I tried doing it with indexes and counting parentheses with no luck. Here is some code I have so far:

final = []
while("(" in string):
final.append(string[string.index("("):string.index(")")+1])
left = string[:string.index("(")]
right = string[string.index(")")+1:]
string = string.replace("+", ";")
string = string.replace("-", ";")
string = string.split(";")
for item in string:
   if item.strip() != "":
     final.append(item)

2 Answers2

0

The regex (https://docs.python.org/2/library/re.html) gives you the shortest and possibility the fastest solution. But, if you prefer a solution that is easier to read and understand try this one:

def split_expr(s):
    l = []
    p =0
    expr = ''
    for c in s:
        if c=='(': p+=1
        if c==')': p-=1
        if (p==0) and (c in '+-*/'):
            l.append(expr)
            expr = ''
        else:
            expr += c
    else:
        l.append(expr)
    return l

You can also see this post (How to split but ignore separators in quoted strings, in python?). It can inspire you for some more elegant solutions.

Community
  • 1
  • 1
Sina
  • 1,888
  • 1
  • 17
  • 16
-1

You might want to use a regular expression for this one. This answer is probably not optimal, but take a look at how to use the re module:

>>> import re
>>> regex = re.compile(r"\s+[\+\*\-\/]\s+")
>>> s = "((1+4)) + (2-1) - 3"
>>> for sub in regex.findall(s):
...     s = s.replace(sub, " ")
>>> s
'((1+4)) (2-1) 3'
>>> s.split()
['((1+4))', '(2-1)', '3']

So, we compile a regular expression using re.compile, this way we can use the regular expression again and again without having to compile it each time. Then we use findall to findall the substrings that satisfy the regular expression, then we take each substring and use the replace function on a string to replace it with a single space. We then use split with the default delimiter set to " " to split the string.

EDIT: Because I totally forgot, you can use re.split, which does all of the above in one fell swoop.

>>> s = "((1+4)) + (2-1) - 3"
>>> regex.split(s)
['((1+4))', '(2-1)', '3']

Thanks @BurhanKhalid :)

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199