-2

Here's an interesting problem I haven't managed to deal with yet.

Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.

The expression is given as a list of numbers and operands. For example [5, 3, '+'] should return 5 + 3 = 8.

For example,

[15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']

should return 5 since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5.

treskov
  • 328
  • 1
  • 4
  • 17
  • Not me, but you link to a page that explains how to implement this... – that other guy Dec 26 '19 at 19:56
  • 1
    I didn't downvote, but this is a reasonably common homework problem, and it's usually expected that you've tried something before coming here – pip install frisbee Dec 26 '19 at 19:57
  • I'm not the one who down voted it but it is probably because you didn't show us what you've tried so far. Show us what you attempted. Please, check ["How to create a Minimal, Complete, and Verifiable example"](https://stackoverflow.com/help/mcve) and ["How to ask"](https://stackoverflow.com/help/how-to-ask). You will get better results by following the tips on those articles. – accdias Dec 26 '19 at 19:57
  • You normally use a stack for that: a number pushes on the stack. An operator pops the two elements of the stack, and pushes the result on the stack. – Willem Van Onsem Dec 26 '19 at 19:58

2 Answers2

3

This code would do the job:

ops = {
    "+": (lambda a, b: a + b),
    "-": (lambda a, b: a - b),
    "*": (lambda a, b: a * b),
    "/": (lambda a, b: a / b)
}


def pol(tokens):
    stack = []

    for token in tokens:
        # Check if the current element is an operator
        if token in ops:
            # Take the last two elements from the list
            arg2 = stack.pop()
            arg1 = stack.pop()
            # Execute an operation based on the current operator
            result = ops[token](arg1, arg2)
            # Append the result to the list in order to keep working with it
            stack.append(result)
        else:
            # If it is a number, just append in to the list
            stack.append(int(token))

    return stack.pop()


print(pol([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']))
enbermudas
  • 1,603
  • 4
  • 20
  • 42
0

Tried to solve it with the string approach.


import re

d = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']

ops = {
    "+": (lambda a, b: a + b),
    "-": (lambda a, b: a - b),
    "*": (lambda a, b: a * b),
    "/": (lambda a, b: a / b)
}

while len(d) > 1:
    s_d = ' '.join(map(str, d))
    l_d = re.findall(r'\d+ \d+ \W', s_d)
    # print(l_d)
    for l1 in l_d:
        l = l1.split(' ')
        a = int(ops[l[-1]](int(l[0]),int(l[1])))
        s_d = s_d.replace(l1, str(int(a)))

    d = s_d.split()

    print(d)
print('----------------------')
print(d[0])