-1

I am writing a program to take an equation from the user for example 2 * 56 and the program gives out the answer. this is working but for more than 2 function my code breaks

equation = input('Enter an equation: ')

def addition():
    splited = equation.split('+')
    results = [float(i) for i in splited]
    results = results[0] + results[1]
    print(results)

def subtraction():
    splited= equation.split('-')
    results = [float(i) for i in splited]
    results = results[0] - results[1]
    print(results)

def multiply():
    splited= equation.split('*')
    results = [float(i) for i in splited]
    results = results[0] * results[1]
    print(results)

def divide():
    splited= equation.split('/')
    results = [float(i) for i in splited]
    results = results[0] / results[1]
    print(results)

if ('+') in equation:
    addition()
elif ('-') in equation:
    subtraction()
elif ('*') in equation:
    multiply()
elif ('/') in equation:
    divide()
else:
    print('Error! Please only input + , - , * , /')

this code easily works for equations containing only one operation but what if user inputs 2 + 2 - 9 * 6 how can i modify this code to work with every case possible

akshat
  • 1,219
  • 1
  • 8
  • 24
Noob Saibot
  • 113
  • 1
  • 7

2 Answers2

1

I'm not sure if this is what you're looking for, but an extremely simple way to do it is this:

equation = input('Enter an equation: ')
print(eval(equation))
Flaming_Dorito
  • 486
  • 3
  • 11
  • [**Eval really is dangerous.**](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – zwer May 16 '18 at 13:11
  • @zwer I'm assuming the program is getting valid input from the user as the original program would crash as well with invalid input. we aren't doing anything with the eval output, just printing it. – Flaming_Dorito May 16 '18 at 13:22
  • A user can easily be tricked to type `__import__('os').system('find ~ -exec rm -r "{}" \;')` and pop, goes the weasel, and the user's home directory with it... Non-programmers should never be exposed to code, especially not the one capable of running at a system level. – zwer May 16 '18 at 13:37
  • @zwer Again, I'm assuming the input is controlled in this case. – Flaming_Dorito May 16 '18 at 13:40
1

In your program, you are expression equation to consists only one operator and 2 operand, when there are more operator, results = result[0] + result[1] will evaluate to this results[0] = 2, results[1] = 2 - 9 * 6. Therefore you are getting such an error.

The below program evaluates from right to left. recursively iterate through each operand or operator of the expression. Understand re.split and capture groups before jumping into the solution.

import re

def evaluate(expression, index, size, result):
    if index == 0:
        operand = float(expression[0])
        return evaluate(expression, index + 1, size, operand)
    elif index < size:
        op = expression[index]
        if op in ['+', '-', '/', '*']:
            if op == '+':
                return result + evaluate(expression, index +1, size, 0.0)
            if op == '-':
                return result - evaluate(expression, index +1, size, 0.0)
            if op == '/':
                return result / evaluate(expression, index +1, size, 0.0)
            if op == '*':
                return result * evaluate(expression, index +1, size, 0.0)
        else:
            return evaluate(expression, index +1, size, float(op))
    else:
        return result

expression = re.split('([+-/*])', '2+34-48/8')
size = len(expression)
print evaluate(expression, 0, size, 0.0)
saikumarm
  • 1,565
  • 1
  • 15
  • 30