'Is there a way to add parentheses to a math expression which is stored in a string? [closed]
I'm trying to figure out a way to add parentheses to a math expression. I don't have any idea how to start with the pseudo code for this issue. Do I need to begin with If statements or is there another way to do this in Java or Kotlin? So basically I want the string to transform.
From this:
val before = "10-2*3/4"
To this:
val after = "((10-2)*3)/4"
Solution 1:[1]
Split the string in chunks, that are alternatively numbers and operators. Assuming that there are n operators, start with n-1 left parenthesis, write first number, first operator, second number, then repeatedly write a right parenthesis, operator, number until you exhaust the string.
E.g. with 10 - 2 * 3 / 4, we have n=3 and output
((
10-2
)*3
)/4
Solution 2:[2]
You can turn your math expression into postfix and then using a stack, add parentheses to it. Here is a Python code snippet demonstrating this:
#infix to postfix
def to_postfix(infix):
s=Stack()
postfix=""
operand_sort={'/':2,
'*':2,
'+':1,
'-':1,}
for token in infix:
if token in '0123456789':
postfix+=(token)
else:
postfix+=(" ")
while (not s.is_empty()) and (operand_sort[s.top()] >= operand_sort[token]):
postfix+=(s.pop())
postfix+=(" ")
s.push(token)
while not s.is_empty():
opToken=s.pop()
postfix+=(" ")
postfix+=(opToken)
return postfix
def setparantheses(postfix):
s=Stack()
items = postfix.split()
for token in items:
if token.isnumeric():
s.push(token)
else:
exp1 = s.pop()
exp2 = s.pop()
s.push("("+exp2+token+exp1+")")
return s.pop()
Sorry I didn't give you Java or pseudocode but you get the idea.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yves Daoust |
| Solution 2 | Laurel |
