📜  波兰符号 python (1)

📅  最后修改于: 2023-12-03 15:11:04.813000             🧑  作者: Mango

Introduction to Polish Notation in Python

What is Polish Notation?

Polish Notation, also known as Prefix Notation, is a way of expressing mathematical expressions where the operator comes before the operands. For example, in infix notation, we would write 3 + 4. In postfix notation, we would write + 3 4. In prefix notation, we would write + 3 4.

Polish notation is named after the Polish logician Jan Łukasiewicz, who introduced it in 1924.

How to use Polish Notation in Python

Python has a built-in module called operator which provides functions for performing arithmetic operations. We can use these functions to evaluate expressions in Polish notation.

Here's an example:

import operator

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

def evaluate(expression):
    tokens = expression.split()
    stack = []

    for token in reversed(tokens):
        if token in operators:
            arg1 = stack.pop()
            arg2 = stack.pop()
            result = operators[token](arg1, arg2)
            stack.append(result)
        else:
            stack.append(float(token))

    return stack.pop()

expression = '+ * 3 4 5'
result = evaluate(expression)
print(result) # Output: 23.0

In this example, we define a dictionary of operators and their corresponding functions from the operator module. We then define a function called evaluate which takes an expression in Polish notation as an argument and returns the result of the expression.

The evaluate function first splits the expression into tokens (operators and operands) using the split method. It then uses a stack to keep track of the operands and their order. We iterate over the tokens in reverse order, so that we can easily extract the operands and their order.

If a token is an operator, we pop two operands from the stack, apply the operator function to them, and push the result back onto the stack. If a token is an operand, we simply push it onto the stack.

Finally, we return the result of the expression, which is the only remaining element on the stack.

Conclusion

Polish Notation is a useful way of expressing mathematical expressions in a concise and unambiguous way. Python's built-in operator module makes it easy to evaluate expressions in Polish notation. With a bit of practice, you can become proficient at using Polish notation in Python.