jfz-2023-s464983/TaskC01/run.py

50 lines
1.7 KiB
Python
Raw Normal View History

2023-12-09 21:52:30 +01:00
import sys
def read_aut_nfa(nfsa_path):
with open(nfsa_path, "r", encoding="utf8") as file:
transisions = {}
accepting_states = set()
for line in file:
parts = line.strip().split()
if len(parts) == 1:
accepting_states.add(int(parts[0]))
else:
state_from = int(parts[0])
state_to = int(parts[1])
symbol = ' ' if len(parts) == 2 else parts[2]
if(state_from, symbol) not in transisions:
transisions[(state_from, symbol)] = []
transisions[(state_from, symbol)].append(state_to)
#print(transisions)
return transisions, accepting_states
def is_accepted_byNFA(transisions, accepting_states, line):
current_states = set([0])
for symbol in line.strip():
next_states = set()
for state in current_states:
if (state, symbol) in transisions:
next_states.update(transisions[(state,symbol)])
current_states = next_states
if len(current_states) == 0:
return "NO"
if any(state in accepting_states for state in current_states):
return "YES"
else:
return "NO"
def process_input(transisions, accepting_states, input_file, output_file):
with open(input_file, "r") as input, open(output_file, "w") as output:
for line in input:
result = is_accepted_byNFA(transisions, accepting_states, line)
output.write(result + '\n')
nfa_file, input_file, output_file = sys.argv[1], sys.argv[2], sys.argv[3]
transisions, accepting_states = read_aut_nfa(nfa_file)
process_input(transisions, accepting_states, input_file, output_file)