r/programminghelp • u/JustARandomPerson902 • Dec 02 '21
Python How to solve order of operations math question using programming?
Hi all, I was wondering if anyone knew how to solve the attached problem using programming? I've tried to do it in Python, but answers in any other languages would also be helpful. Thanks!
"Place the missing parentheses so that:
60 - 18 / 2 + 4 + 15 /3 = 12"
5
Upvotes
1
u/KuntaStillSingle Dec 02 '21 edited Dec 02 '21
This is /r/shittyprogramming tier but it works:
#input the 'non-simple' side of the equation in ordinary notation,
#get it back in postfix https://en.wikipedia.org/wiki/Reverse_Polish_notation
#uses algorithm described here http://csis.pace.edu/~wolf/CS122/infix-postfix.htm
def get_postfix_notation(infix_notation):
operator_stack = []
output_string = ""
for i in range(0, len(infix_notation)):
digit = infix_notation[i]
if digit in "0123456789 " : #1. print operands as they arrive
output_string += infix_notation[i]
continue
if not digit in "+/*-()" : #just a sentinel to discard unrecognized characters
continue
if digit == ')':
#4. if it is right paran, pop operator until you see left paran,
#discard parans
while operator_stack[-1] != '(':
output_string += operator_stack.pop()
operator_stack.pop()
continue
if len(operator_stack) == 0 or operator_stack[-1] == '(':
#2. if the stack is empty or contains a left paran, push operator
operator_stack.append(digit)
continue
if digit == '(': #3. if it is left paran, push operator
operator_stack.append(digit)
continue
if operator_stack[-1] in "+-" and digit in "*/":
#5. if it is higher precedence than top of stack, push it
operator_stack.append(digit)
continue
if (operator_stack[-1] in "+-" and digit in "+=") or (operator_stack[-1] in "*/" and digit in "*/"):
#6. if it is equal precedence, pop then push
output_string += operator_stack.pop()
operator_stack.append(digit)
continue
#7. if the incoming operator is lower priority, pop, then test again:
continue_checking = True
while (continue_checking == True):
#print(digit, operator_stack)
if len(operator_stack) == 0 :
operator_stack.append(digit)
break
if(operator_stack[-1] in "*/"):
output_string += operator_stack.pop()
continue
if(operator_stack[-1] in "+-"):
output_string += operator_stack.pop()
operator_stack.append(digit)
continue_checking = False
if(operator_stack[-1] == "("):
operator_stack.append(digit)
continue_checking = False
#8. finally pop all operators
while len(operator_stack) != 0 : output_string += operator_stack.pop()
return output_string
def solve_postfix_notation(postfix_notation): #uses method explained here: https://www.free-online-calculator-use.com/postfix-evaluator.html
value_string = ""
values = []
for i in range(0, len(postfix_notation)):
digit = postfix_notation[i]
if digit in "0123456789": #if it is a numerical digit it is part of a value
value_string += digit
continue
if len(value_string) != 0: #if it is not a numerical digit then whatever value we started is finished
values.append(int(value_string))
value_string = ""
#intentionally no continue here
if digit == "+":
right_operand = values.pop()
left_operand = values.pop()
values.append(left_operand + right_operand)
continue
if digit == "-":
right_operand = values.pop()
left_operand = values.pop()
values.append(left_operand - right_operand)
continue
if digit == "*":
right_operand = values.pop()
left_operand = values.pop()
values.append(left_operand * right_operand)
continue
if digit == "/":
right_operand = values.pop()
left_operand = values.pop()
values.append(left_operand / right_operand)
return values[0]
def permute_parans_until_success(problem, solution, pairs = 1):
for left_index in range(0, len(problem)):
for right_index in range(left_index +1, len(problem)+1):
#our left paranthese needs to precede either a digit(1-9) or another paranthese, and the right one needs to follow a digit or another paranthese
if problem[left_index] in "0123456789()" and problem[right_index-1] in "0123456789()":
#right paran also needs to be last index or not followed by a digit
if right_index < len(problem):
if problem[right_index] in "0123456789(B":
continue
#left paran also needs to be first index or not preceded by a digit
if left_index != 0:
if problem[left_index -1] in "0123456789":
continue
problem_w_parans = problem[:left_index] + '(' + problem[left_index:right_index] + ')' + problem[right_index:]
#print(problem_w_parans)
#print(solve_postfix_notation(get_postfix_notation(problem_w_parans)) - solution)
if pairs != 1:
next_level_solution = permute_parans_until_success(problem_w_parans, solution, pairs -1)
if(next_level_solution) == None:
continue
return next_level_solution
if solve_postfix_notation(get_postfix_notation(problem_w_parans)) == solution : #found a combination that works
return problem_w_parans
return None
problem = "60 - 18 / 2 + 4 + 15 / 3 = 12"
#problem = "( 60 - 18 ) / ( 2 + 4 ) + 15 / 3 = 12"
equals_index = problem.index('=')#find the equals sign
#get a substring starting one character afterwards and convert to integer
solution = int(problem[equals_index + 1:])
#this assumes the 'simple' side of the equation is one integer value on the right side of the equal sign
#now that we have solution isolate the unsimplified side
problem = problem[:equals_index -1]
postfix_notation = get_postfix_notation(problem)
print(postfix_notation)
print(solve_postfix_notation(postfix_notation))
for i in range (2, 3):
solved = permute_parans_until_success(problem, solution, i)
if not solved == None:
print(solved)
print(solve_postfix_notation(get_postfix_notation(solved)))Edit: uses floating point now, trimmed some more redundant cases, should be no more empty parantheses but you can still get a parantheses wrapping only a single value (i.e. (60) + 1 = 61 ) This assumes the right side is already simplified and only supports +-*/ operators.
2
u/DeVoto Dec 02 '21
Is the task to put in the above equation and output/return the number 12? Or to output a string of the equation with the correct parenthesis?