V
V
Vasily Vasilyev2017-08-27 14:47:01
Java
Vasily Vasilyev, 2017-08-27 14:47:01

Convert from reverse Polish notation to regular notation. How?

At the input - the reverse Polish notation of the formula (on the stack). You need to convert it to normal.
Example:

Получаем:  
2 3 + 6 2 / 5 2 * - +

Отдаем: 
2+3+6/2-5*2

PS: Perhaps the question will seem stupid, but, alas, I heard about this record for the first time yesterday. Understand, forgive, help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2017-08-27
@Basil_Dev

stack = "2 3 + 6 2 / 5 2 * - +".split()

def f():
    op = stack.pop()
    if op.isdigit():
        return float(op)
    else:
        y = f()
        x = f()
        if op == "+":
            return x + y
        if op == "-":
            return x - y
        if op == "*":
            return x * y
        if op == "/":
            return x / y

print(f())

Oh yes, you need the line:
stack = "2 3 + 6 2 / 5 2 * - +".split()
def g():
    op = stack.pop()
    if op.isdigit():
        return op
    else:
        y = g()
        x = g()
        return ''.join(("(", x, op, y, ")")) # *

print(g())

* Rsa97 pointed out the need for brackets - some of them are redundant, but it's better to overdo it than not.

V
Vladimir Olohtonov, 2017-08-27
@sgjurano

https://learnc.info/adt/binary_tree_traversal.html
This can be described as a binary tree traversal, in its original form: post-order (left subtree, right subtree, operation), in the final form: in-order (left subtree, operation, right subtree).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question