Skip to content

Instantly share code, notes, and snippets.

@KevinAlavik
Created June 27, 2023 10:38
Show Gist options
  • Save KevinAlavik/d3a31c52854e34aa256d0305390c9d59 to your computer and use it in GitHub Desktop.
Save KevinAlavik/d3a31c52854e34aa256d0305390c9d59 to your computer and use it in GitHub Desktop.
Simple lexer and parser for a calculator in python. You can use the same logic to create your own programming language
tokens = ["+", "-", "/", "*", "^"]
def parse(source):
characters = list(source)
final = []
for char in characters:
if char.isdigit():
final.append(float(char))
else:
for token in tokens:
if char == token:
final.append(token)
break
else:
raise SyntaxError("Invalid character '" + char + "'")
return final
def evaluate(parsed):
stack = []
for item in parsed:
if isinstance(item, float) or (isinstance(item, str) and item.isdigit()):
stack.append(float(item))
else:
stack.append(item)
# Initialize the result with the first number in the stack
result = stack[0]
for i in range(1, len(stack), 2):
operator = stack[i]
operand = stack[i + 1]
if operator == "+":
result += operand
elif operator == "-":
result -= operand
elif operator == "/":
result /= operand
elif operator == "*":
result *= operand
elif operator == "^":
result **= operand
print(result)
while True:
source = input("> ")
if not source:
break
try:
parsed = parse(source)
evaluate(parsed)
except SyntaxError as e:
print("Syntax Error: " + str(e))
except IndexError as e:
print("Index Error: " + str(e))
except ValueError as e:
print("Value Error: " + str(e))
@luisespino
Copy link

The code has an operator precedence problem.

@KevinAlavik
Copy link
Author

The code has an operator precedence problem.

@luisespino it was a simple test to showcase a tokenizer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment