-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLab-1
62 lines (53 loc) · 1.61 KB
/
Lab-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
while True:
print("Write infix notated expression or '-exit': ")
line = input()
def Tokenize(line):
numbers_buffer = []
tokens = []
for s in line:
if s.isdigit():
numbers_buffer.append(s)
elif s == "+" or s == "-" or s == "*" or s =="/" or s == "(" or s ==')' or s == "":
if len(numbers_buffer) != 0:
token = ""
for i in numbers_buffer:
token += i
numbers_buffer.clear()
tokens.append(token)
if s != '':
tokens.append(s)
print(tokens)
return tokens
def InfixToPostfix(tokens):
postFix = ''
s = []
for c in tokens:
if c in "123456789":
postFix += c
elif c in "+-":
if len(s) == 0:
s.append(c)
elif s[0] == '(':
s.append(c)
elif c in "*/":
if len(s) == 0:
s.append(c)
elif s[0] in "+-(":
s.append(c)
elif c == "(":
s.append(c)
elif c == ")":
postFix += s.pop()
s.pop()
else:
print("Error")
print(postFix)
return postFix
def CalsulatePostfix(postfix):
print("")
if line == '-exit':
break
else:
infixTokens = Tokenize(line)
postfixTokens = InfixToPostfix(infixTokens)
result = CalsulatePostfix(postfixTokens)