-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogicOperation.py
123 lines (108 loc) · 3.16 KB
/
LogicOperation.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def isString(n: str):
return (n[0] == "\"" and n[-1] == "\"" and n.count('"') == 2)
def cprVal(n):
if n in ["not"]:
return 2
if n in ["and", "or"]:
return 1
if n in ["!=", "==", "<=", ">=", "<", ">"]:
return 3
match n:
case "+" | "-": return 4
case "*" | "/": return 5
case "^": return 6
def checkBracketLs(n: list):
openBracket = n.count("(")
closeBracket = n.count(")")
if openBracket > closeBracket:
for i in range(openBracket - closeBracket):
n.append(")")
else:
for i in range(closeBracket - openBracket):
n.insert(0, "(")
return n
def isOpLgc(c):
cprOp = ["and", "or", "not", "!=", "==", "<=", ">=",
"<", ">", "+", "/", "*", "-", "^", "%", "(", ")"]
return c in cprOp
def logicPostfix(ls: list):
n = checkBracketLs(ls)
result = []
aux = []
for c in n:
if c in [" ", ""]:
continue
if not isOpLgc(c):
result.append(c)
elif c == '(':
aux.append(c)
elif c == ')':
while len(aux) > 0 and aux[-1] != '(':
result.append(aux.pop())
aux.pop()
else:
while len(aux) > 0 and aux[-1] != "(" and cprVal(aux[-1]) >= cprVal(c):
result.append(aux.pop())
aux.append(c)
while len(aux) > 0:
result.append(aux.pop())
return result
def calculateLogic(n: list):
# print("calculateLogic", n)
OPERATION = {
"and": lambda a, b: int(a and b),
"or": lambda a, b: int(a or b),
"not": lambda a: int(not a),
"!=": lambda a, b: int(a != b),
"==": lambda a, b: int(a == b),
"<=": lambda a, b: int(a <= b),
">=": lambda a, b: int(a >= b),
"<": lambda a, b: int(a < b),
">": lambda a, b: int(a > b),
"+": lambda a, b: a + b,
"/": lambda a, b: a / b,
"*": lambda a, b: a * b,
"-": lambda a, b: a - b,
"^": lambda a, b: a ** b,
"%": lambda a, b: a % b
}
result = []
for c in n:
# print("c", c)
# print("result", result)
try:
result.append(float(c))
continue
except:
pass
if isString(c):
result.append(c[1:-1])
continue
a = 0
b = result.pop()
if c != "not":
if not (len(result) == 0 or isOpLgc(result[-1])):
a = result.pop()
# print("a", a)
# print("b", b)
a = int(a) if type(a) == float and a % 1 == 0 else a
b = int(b) if type(b) == float and b % 1 == 0 else b
# print("1 a", a)
# print("1 b", b)
try:
if c == "not":
tmp = OPERATION[c](b)
else:
tmp = OPERATION[c](a, b)
result.append(tmp)
except Exception as e:
print("error:", e)
return None
# print("result after op", result)
res = result.pop()
if type(res) == float:
if res.is_integer():
return int(res)
if type(res) == str:
return "\"" + res + "\""
return res