Skip to content

Commit 8f0494b

Browse files
authored
Add files via upload
1 parent 796a5be commit 8f0494b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

shunting-yard/calc.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import re
2+
import sys
3+
4+
def get_precedence(op):
5+
precedences = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
6+
return precedences.get(op, 0)
7+
8+
def infix_to_postfix(expression):
9+
output = []
10+
stack = []
11+
tokens = tokenize(expression)
12+
13+
for token in tokens:
14+
if token.isnumeric():
15+
output.append(token)
16+
elif token == '(':
17+
stack.append(token)
18+
elif token == ')':
19+
while stack and stack[-1] != '(':
20+
output.append(stack.pop())
21+
stack.pop() # Pop the left parenthesis
22+
else:
23+
while stack and get_precedence(stack[-1]) >= get_precedence(token):
24+
output.append(stack.pop())
25+
stack.append(token)
26+
27+
while stack:
28+
output.append(stack.pop())
29+
30+
return output
31+
32+
def tokenize(expression):
33+
# Regular expression pattern for numbers and operators
34+
token_pattern = r'\d+|\+|-|\*|/|\(|\)|\^'
35+
tokens = re.findall(token_pattern, expression)
36+
return tokens
37+
38+
def evaluate_postfix(expression):
39+
stack = []
40+
41+
for token in expression:
42+
if token.isdigit():
43+
stack.append(int(token))
44+
else:
45+
b = stack.pop()
46+
a = stack.pop()
47+
if token == '+':
48+
stack.append(a + b)
49+
elif token == '-':
50+
stack.append(a - b)
51+
elif token == '*':
52+
stack.append(a * b)
53+
elif token == '/':
54+
stack.append(a / b)
55+
elif token == '^':
56+
stack.append(pow(a, b))
57+
58+
return stack.pop()
59+
60+
while True:
61+
if len(sys.argv) != 2:
62+
infix_expression = input("")
63+
else:
64+
infix_expression = sys.argv[1]
65+
66+
postfix_expression = infix_to_postfix(infix_expression)
67+
result = evaluate_postfix(postfix_expression)
68+
print(result)
69+
if len(sys.argv) == 2:
70+
exit(result)

0 commit comments

Comments
 (0)