jfz-2023-s473579/TaskC06/test.py

58 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

def write_answer(answer, output_file):
with open(output_file, 'a', encoding='utf-8') as file:
file.write(answer+'\n')
def run_automaton(file_path, end_positions, output_file):
transitions = {}
# Чтение информации из файла
with open(file_path, 'r', encoding='utf-8') as file:
with open(output_file, 'w', encoding='utf-8') as file_writed:
lines = file.readlines()
for line in lines:
if line.strip(): # Пропускаем пустые строки
parts = line.split()
state_from = int(parts[0])
if len(parts) > 1:
state_to = int(parts[1])
if len(parts) == 3:
symbol = parts[2]
transitions.setdefault(state_from, []).append((symbol, state_to))
else:
transitions[state_from] = []
def explore_paths(current_state, current_word):
if current_state not in transitions:
if str(current_state) in end_positions:
write_answer(current_word, output_file)
return
possible_transitions = transitions[current_state]
for transition_symbol, next_state in possible_transitions:
explore_paths(next_state, current_word + transition_symbol)
# Начинаем с начального состояния
explore_paths(0, "")
def what_is_the_ended_positions(file_path):
array = []
with open(file_path, 'r', encoding='utf-8') as file:
for row in file:
line = row.strip().split('\t')
if len(line) == 1:
array += line
return array
# Указываем путь к файлу
file_path = "small.in"
output_file = "small.out"
# Получаем конечные позиции из файла
end_positions = what_is_the_ended_positions(file_path)
# Запускаем автомат
run_automaton(file_path, end_positions, output_file)