I will not write the full code for that, but here are the steps you have to take:
If your input contains parentheses, you should find the parentheses that do not have parentheses inside them. You can do this using the
re
module, with
re.search
:
import re
expression = "(6+(7+8))"
match = re.search("\\(([^()]+)\\)", expression)
print(match.group(0))
print(match.group(1))
So you perform that on your actual input.
.group(1)
will give you the simple expression without parentheses,
.group(0)
will give you the expression with its parentheses. You then need to evaluate the expression of
.group(1)
(which isn't hard, you have a function for that already) and then, in the original string, you have to replace the value of
.group(0)
with the result of the evaluation of
.group(1)
, using the
.replace
method on strings.
But there may be more parentheses pairs in one expression, so you have to repeat the above process until there are no more parentheses in the expression.