49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
![]() |
import sys
|
||
|
|
||
|
def load_data(file_path):
|
||
|
dfa = {}
|
||
|
with open(file_path, 'r') as file:
|
||
|
for line in file:
|
||
|
split_data = line.strip().split('\t')
|
||
|
if len(split_data) == 3:
|
||
|
state, next_state, symbol = split_data
|
||
|
key = (int(state), symbol)
|
||
|
dfa[key] = int(next_state)
|
||
|
|
||
|
return dfa
|
||
|
|
||
|
def is_accepted(dfa, input_str, current_state, accepting_states):
|
||
|
for i, symbol in enumerate(input_str):
|
||
|
key = (current_state, symbol)
|
||
|
if key in dfa:
|
||
|
current_state = dfa[key]
|
||
|
elif (current_state, '<eps>') in dfa: # Check for <eps> transition
|
||
|
current_state = dfa[(current_state, '<eps>')]
|
||
|
else:
|
||
|
# If there is no transition for the current symbol or <eps>, reject the string
|
||
|
return False
|
||
|
|
||
|
# If it's the last symbol and the current state is not accepting, check for <eps> transition
|
||
|
if i == len(input_str) - 1 and current_state not in accepting_states:
|
||
|
if (current_state, '<eps>') in dfa:
|
||
|
current_state = dfa[(current_state, '<eps>')]
|
||
|
if current_state in accepting_states:
|
||
|
return True
|
||
|
|
||
|
return current_state in accepting_states
|
||
|
|
||
|
|
||
|
# Set of accepting states
|
||
|
accepting_states = {2,5}
|
||
|
|
||
|
dfa_file = sys.argv[1]
|
||
|
dfa = load_data(dfa_file)
|
||
|
|
||
|
for line in sys.stdin:
|
||
|
input_str = line.strip()
|
||
|
start_state = 0
|
||
|
if is_accepted(dfa, input_str, start_state, accepting_states):
|
||
|
print("YES", input_str)
|
||
|
else:
|
||
|
print("NO", input_str)
|