This is an interview question, for which I did not find any satisfactory answers on stackoverflow or outside. Problem statement:
Given an arithmetic
Just in case someone finds this question while looking for a quick and easy solution: If your expression is sanitized and your language (or library) provides an eval function for your expression, you could just try if removing a pair of brackets will change the value of your expression. If it does, you'll have to keep the brackets. If it does not, you can remove them.
However, keep in mind, this is not an efficient solution, of course, but rather the "brute force" path.
Here's an exemplary implementation in Python which works for integers and the built-in eval:
def remove_brackets(term):
a = 0
while True:
# Find opening bracket
try:
a = term.index("(", a)
except ValueError:
# No (more) opening brackets found
break
# Find corresponding closing bracket
b = a
while True:
b = term.index(")", b + 1)
if term[a + 1:b].count("(") == term[a + 1:b].count(")"):
break
# Assemble new term by removing current pair of brackets
new_term = term[:a] + term[a + 1:b] + term[b + 1:]
# If new term produces a different value, keep term as it is and try with the next pair of brackets
if eval(term) != eval(new_term):
a += 1
continue
# Adopt new term
term = new_term
return term
Example calls:
>>> remove_brackets("1 + (2 * 3)")
'1 + 2 * 3'
>>> remove_brackets("1 + (2 * 3) / 4")
'1 + 2 * 3 / 4'
>>> remove_brackets("1 + (2 * 3) / 4 / (5 * 6)")
'1 + 2 * 3 / 4 / (5 * 6)'