Created
December 10, 2022 05:55
-
-
Save mafshin/367fb266d18e704b393ac2430eaa3010 to your computer and use it in GitHub Desktop.
A simple parser in Python by Chat GPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import operator | |
# Define a dictionary of supported operations and their corresponding | |
# functions from the operator module | |
operators = { | |
"+": operator.add, | |
"-": operator.sub, | |
"*": operator.mul, | |
"/": operator.truediv, | |
} | |
def calculate(expression): | |
# Convert the expression to a list of tokens | |
tokens = expression.split() | |
# Iterate over the tokens, using a stack to keep track of intermediate | |
# results and operations | |
stack = [] | |
for token in tokens: | |
# If the token is a number, convert it to an integer and append it | |
# to the stack | |
if token.isdigit(): | |
stack.append(int(token)) | |
# If the token is an operator, pop the last two items from the | |
# stack and apply the operator to them, then append the result | |
# to the stack | |
elif token in operators: | |
right = stack.pop() | |
left = stack.pop() | |
result = operators[token](left, right) | |
stack.append(result) | |
# Return the result of the calculation | |
return stack[0] | |
# Test the calculator | |
print(calculate("2 + 3 * 4")) # 14 | |
print(calculate("10 - 2 / 3")) # 9.333333333333334 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment