2

I have a list in python that looks something like this:

list = [5, "-", 4, "*", 8]

I would like to calculate the math problem in the list so:

anwser = 5 - 4 * 8

So the variable "anwser" is -27.

MY_name
  • 25
  • 5
  • Possible duplicate of [Evaluate math equations from unsafe user input in Python](https://stackoverflow.com/questions/26505420/evaluate-math-equations-from-unsafe-user-input-in-python) – zwer Feb 10 '19 at 13:57
  • 1
    **DO NOT** use [`eval()`](https://docs.python.org/3/library/functions.html#eval) for this - it's dangerous and prone to errors. – zwer Feb 10 '19 at 13:57
  • Parse it into an expression tree. Walk the tree and evaluate. The answer could also be 8, depending on how to implement precedence rules. – duffymo Feb 10 '19 at 19:23

3 Answers3

2

This is what you call a Infix notation (https://en.wikipedia.org/wiki/Infix_notation)

You can use a stack to evaluate it. I found a gist here which might help (https://gist.github.com/nava45/6333409#file-infix-expression-evaluation)

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
2

Evaluating an equation with priority of operations requires a parser.

Fortunately, writing a parser for basic arithmetic, that is addition and multiplication, can be achieved fairly simply without the use of parsing tools.

Code

import operator

ops = {
    '-': operator.sub,
    '+': operator.add,
    '*': operator.mul,
    '/': operator.truediv
}

def parse_mult(equation):
    equation = iter(equation)
    value = next(equation)
    for token in equation:
        if token == '*' or token == '/':
            op = ops[token]
            value = op(value, next(equation))
        else:
            yield value
            yield token
            value = next(equation)
    yield value

def parse(equation):
    equation = parse_mult(equation)
    value = next(equation)
    for token in equation:
        op = ops[token]
        value = op(value, next(equation))
    return value

Example

equation_list = [5, "-", 4, "*", 8]
print(parse(equation_list))

Output

-27

If you ever need to parse equations with more than two levels of priority, than an external parsing tool may become necessary.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

This will work:

eval(''.join([str(x) for x in list]))

But be careful using eval!

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75