djfz-2019-s426197/TaskB02/run.py

53 lines
2.3 KiB
Python

import re
import sys
atandt_desc_pattern = re.compile(r"^([0-9]+)[ \t]([0-9]+)[ \t](\S+)([ \t][0-9]+(\.[0-9]+)?)?$") #^([0-9]+)[ \t]([0-9]+)[ \t](\S+)([ \t][0-9]+(\.[0-9]+)?)?$
atandt_accepted_state_pattern = re.compile(r"^[0-9]+$")
current_state = 0
accept_states = []
state_move = {}
for line in sys.stdin:
line = line.replace('\n', '')
move = atandt_desc_pattern.match(line)
succes = atandt_accepted_state_pattern.match(line)
if move:
if move.group(4):
state_move[(int(move.group(1)), move.group(3))] = (int(move.group(2)), float(move.group(4)))
else:
state_move[(int(move.group(1)), move.group(3))] = (int(move.group(2)), 0)
if succes:
accept_states.append(int(line))
print(state_move)
with open(sys.argv[1], 'r') as f:
for word in f:
# starting with from 0 node because that is atandt standard
current_state = 0
word = word.replace('\n', '')
character_number = 0
# checking what is next state based on current character from word
while character_number < len(word):
#print('State: {current_state} and character: {char} on index {character_number}'.format(current_state = current_state, char = word[character_number], character_number = character_number))
if ((current_state, word[character_number]) in state_move):
current_state = state_move[(current_state, word[character_number])][0]
character_number += 1
# if there is epsilon program move to pointed node but didnt count epsilon as character
elif ((current_state, '<eps>') in state_move):
current_state = state_move[(current_state, '<eps>')][0]
else:
current_state = -1
character_number += 1
#print('State after {char} letter: {current_state} and index {character_number}'.format(current_state = current_state, char = word[character_number - 1], character_number = character_number))
#print('State after consuming whole word: {current_state}'.format(current_state = current_state))
while ((current_state, '<eps>') in state_move):
current_state = state_move[(current_state, '<eps>')][0]
if (current_state in accept_states):
print("YES " + word)
else:
print("NO " + word)