-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic gate Simulator
More file actions
68 lines (61 loc) · 2.56 KB
/
logic gate Simulator
File metadata and controls
68 lines (61 loc) · 2.56 KB
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
def LogicEval(p: bool, q: bool, r: bool, expression: str) -> bool:
# Dictionary to store variable values
variables = {'p': p, 'q': q, 'r': r}
# Convert the expression into a list of tokens (words and symbols)
tokens = []
i = 0
while i < len(expression):
if expression[i].isalpha(): # If it's a letter (p, q, r, not, and, or)
word = ""
while i < len(expression) and expression[i].isalpha():
word += expression[i]
i += 1
tokens.append(word)
elif expression[i] in "()": # Parentheses
tokens.append(expression[i])
i += 1
else: # Spaces and unknown characters
i += 1 # Skip them
# Convert variable names to their boolean values
for j in range(len(tokens)):
if tokens[j] in variables:
tokens[j] = variables[tokens[j]]
# Process NOT operations first
i = 0
while i < len(tokens):
if tokens[i] == "not" and i + 1 < len(tokens):
tokens[i] = not tokens[i + 1]
tokens.pop(i + 1) # Remove the next token (variable)
else:
i += 1
# Process AND operations
i = 0
while i < len(tokens):
if tokens[i] == "and" and i - 1 >= 0 and i + 1 < len(tokens):
tokens[i - 1] = tokens[i - 1] and tokens[i + 1]
tokens.pop(i) # Remove "and"
tokens.pop(i) # Remove the next value
else:
i += 1
# Process OR operations
i = 0
while i < len(tokens):
if tokens[i] == "or" and i - 1 >= 0 and i + 1 < len(tokens):
tokens[i - 1] = tokens[i - 1] or tokens[i + 1]
tokens.pop(i) # Remove "or"
tokens.pop(i) # Remove the next value
else:
i += 1
# The final result should be the only element left
return tokens[0]
# Test Cases
print(LogicEval(True, True, True, "p and q")) # Expected: True
print(LogicEval(True, False, True, "p or q")) # Expected: True
print(LogicEval(False, True, True, "not p")) # Expected: True
print(LogicEval(True, False, True, "p and (q or r)")) # Expected: True
print(LogicEval(True, True, False, "(p and q) or (not r)")) # Expected: True
print(LogicEval(True, True, True, "not (p and q)")) # Expected: False
print(LogicEval(True, False, True, "p and not q")) # Expected: True
print(LogicEval(True, False, True, "(p or q) and r")) # Expected: True
print(LogicEval(False, True, True, "not p or (q and r)")) # Expected: True
print(LogicEval(True, True, False, "(not p and q) or (p and not r)")) # Expected: True