djfz-2023-s464933/TaskC03/run.py

53 lines
1.6 KiB
Python
Raw Normal View History

2023-11-19 22:42:11 +01:00
import sys
2023-12-17 21:57:42 +01:00
class NFA:
def __init__(self):
self.initial_state = '0'
self.final_states = set()
2023-11-19 22:42:11 +01:00
2023-12-17 21:57:42 +01:00
self.transitions = dict()
self.alphabet = set()
2023-11-19 22:42:11 +01:00
def add_transition(self, state_from, state_to, symbol):
if state_from in self.transitions.keys():
if symbol not in self.transitions[state_from].keys():
self.transitions[state_from][symbol] = {state_to}
else:
self.transitions[state_from][symbol] |= {state_to}
else:
self.transitions[state_from] = dict()
self.transitions[state_from][symbol] = {state_to}
def add_final_state(self, state):
self.final_states.add(state)
2023-12-17 21:57:42 +01:00
def get_final_states(self, string):
current_states = {self.initial_state}
for symbol in string:
current_states = {state for current_state in current_states for state in self.transitions.get(current_state, {}).get(symbol, set())}
return current_states
def accepts(self, string):
return any(final_state in self.final_states for final_state in self.get_final_states(string))
2023-11-19 22:42:11 +01:00
2023-12-17 21:57:42 +01:00
nfa = NFA()
2023-11-19 22:42:11 +01:00
table = open(sys.argv[1])
for line in table:
2023-12-17 21:57:42 +01:00
line = line.rstrip('\n')
2024-01-03 19:19:38 +01:00
if len(line.split(' ')) == 3:
a, b, c = line.split(' ')
2023-12-17 21:57:42 +01:00
c = c.replace("'","")
c = list(c)
for x in c:
nfa.add_transition(a, b, x)
nfa.alphabet.add(x)
2024-01-03 19:19:38 +01:00
elif len(line.split(' ')) == 1:
2023-12-17 21:57:42 +01:00
nfa.add_final_state(line)
2023-11-19 22:42:11 +01:00
else:
2023-12-17 21:57:42 +01:00
assert False
2023-11-19 22:42:11 +01:00
for line in sys.stdin:
2023-12-17 21:57:42 +01:00
print("YES" if nfa.accepts(line.strip()) else "NO")