mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 23:11:09 +00:00
c909da9b08
* pre-commit: Upgrade psf/black for stable style 2023 Updating https://github.com/psf/black ... updating 22.12.0 -> 23.1.0 for their `2023 stable style`. * https://github.com/psf/black/blob/main/CHANGES.md#2310 > This is the first [psf/black] release of 2023, and following our stability policy, it comes with a number of improvements to our stable style… Also, add https://github.com/tox-dev/pyproject-fmt and https://github.com/abravalheri/validate-pyproject to pre-commit. I only modified `.pre-commit-config.yaml` and all other files were modified by pre-commit.ci and psf/black. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
60 lines
1.2 KiB
Python
60 lines
1.2 KiB
Python
"""
|
|
Python3 program to evaluate a prefix expression.
|
|
"""
|
|
|
|
calc = {
|
|
"+": lambda x, y: x + y,
|
|
"-": lambda x, y: x - y,
|
|
"*": lambda x, y: x * y,
|
|
"/": lambda x, y: x / y,
|
|
}
|
|
|
|
|
|
def is_operand(c):
|
|
"""
|
|
Return True if the given char c is an operand, e.g. it is a number
|
|
|
|
>>> is_operand("1")
|
|
True
|
|
>>> is_operand("+")
|
|
False
|
|
"""
|
|
return c.isdigit()
|
|
|
|
|
|
def evaluate(expression):
|
|
"""
|
|
Evaluate a given expression in prefix notation.
|
|
Asserts that the given expression is valid.
|
|
|
|
>>> evaluate("+ 9 * 2 6")
|
|
21
|
|
>>> evaluate("/ * 10 2 + 4 1 ")
|
|
4.0
|
|
"""
|
|
stack = []
|
|
|
|
# iterate over the string in reverse order
|
|
for c in expression.split()[::-1]:
|
|
# push operand to stack
|
|
if is_operand(c):
|
|
stack.append(int(c))
|
|
|
|
else:
|
|
# pop values from stack can calculate the result
|
|
# push the result onto the stack again
|
|
o1 = stack.pop()
|
|
o2 = stack.pop()
|
|
stack.append(calc[c](o1, o2))
|
|
|
|
return stack.pop()
|
|
|
|
|
|
# Driver code
|
|
if __name__ == "__main__":
|
|
test_expression = "+ 9 * 2 6"
|
|
print(evaluate(test_expression))
|
|
|
|
test_expression = "/ * 10 2 + 4 1 "
|
|
print(evaluate(test_expression))
|