jfz-2023-s474155/TaskC00/run.py
2023-11-25 22:29:42 +01:00

66 lines
1.7 KiB
Python

import sys
sys.setrecursionlimit(4500)
def AddTransition(transitions, state_from, state_to, symbol):
if state_from in transitions:
if symbol not in transitions[state_from]:
transitions[state_from][symbol] = {state_to}
else:
transitions[state_from][symbol] |= {state_to}
else:
transitions[state_from] = {symbol: {state_to}}
def AddFinalState(final_states, state):
final_states.add(state)
def GetFinalStates(transitions, final_states, string, current_state):
if not string:
return current_state if current_state in final_states else -1
symbol, rest = string[0], string[1:]
try:
for state in transitions[current_state][symbol]:
result = GetFinalStates(transitions, final_states, rest, state)
if result != -1:
return result
except KeyError:
return -1
return -1
def IsAccepted(transitions, final_states, string, initial_state):
final_state = GetFinalStates(transitions, final_states, string, initial_state)
return final_state in final_states
transitions = {}
final_states = set()
with open(sys.argv[1]) as table:
for line in table:
line = line.rstrip()
if len(line.split('\t')) == 3:
a, b, c = line.split('\t')
AddTransition(transitions, a, b, c)
else:
AddFinalState(final_states, line)
with open(sys.argv[2], 'r', encoding="utf-8") as input_data, open(sys.argv[3], 'w', encoding="utf-8") as output_data:
for line in input_data:
line = line.rstrip()
if IsAccepted(transitions, final_states, line, '0'):
output_data.write('YES\n')
else:
output_data.write('NO\n')