djfz-2019-s426197/TaskB05/run.py

68 lines
2.0 KiB
Python
Raw Permalink Normal View History

2019-12-06 10:45:47 +01:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
# Regex pattern for reading atandt format
2019-12-13 17:56:57 +01:00
atandt_desc_pattern = re.compile(r"^([0-9]+)[ \t]([0-9]+)[ \t](\S+)") #^([0-9]+)\t([0-9]+)\t(\S+)$ regex for tab separated columns
2019-12-06 10:45:47 +01:00
atandt_accepted_state_pattern = re.compile(r"^[0-9]+$")
current_state = 0
accept_states = set()
state_move = set()
# function that filters set by starting node and returns all edges that starts in that node
def filter_set(xs, filtered_value):
return set(filter(lambda x: x[0] == filtered_value, xs))
def dfs(graph, start):
visited = set()
2019-12-13 17:56:57 +01:00
stack = []
2019-12-06 10:45:47 +01:00
for el in filter_set(state_move, 0):
2019-12-13 17:56:57 +01:00
stack.append(el)
2019-12-06 10:45:47 +01:00
while stack:
edge = stack.pop()
#print('Current edge: {edge}'.format(edge = edge))
#return immediately if cycle is detected
if edge[0] == edge[2]:
return [-1]
2019-12-13 17:56:57 +01:00
if edge[2] in accept_states:
visited = set()
2019-12-06 10:45:47 +01:00
if edge not in visited:
visited.add(edge)
children = set()
for val in filter_set(state_move, edge[2]):
2019-12-13 17:56:57 +01:00
stack.append(val)
#print('Stack: {stack}'.format(stack = stack))
#print('Visited: {visited}'.format(visited = visited))
2019-12-06 10:45:47 +01:00
else:
2019-12-13 17:56:57 +01:00
return [-2]
2019-12-06 10:45:47 +01:00
return visited
2019-12-13 17:56:57 +01:00
#print("Start program")
# load atand format from stdin
2019-12-06 10:45:47 +01:00
for line in sys.stdin:
line = line.replace('\n', '')
2019-12-13 17:56:57 +01:00
#print(line)
2019-12-06 10:45:47 +01:00
move = atandt_desc_pattern.match(line)
succes = atandt_accepted_state_pattern.match(line)
if move:
node = str(move.group(3))
2019-12-06 10:45:47 +01:00
state_move.add((int(move.group(1)), node, int(move.group(2))))
if succes:
accept_states.add(int(line))
2019-12-13 14:13:59 +01:00
#print('Moves: {state_move}'.format(state_move = state_move))
#print('Accept states: {accept_states}'.format(accept_states = accept_states))
2019-12-06 10:45:47 +01:00
vis = dfs(state_move, 0)
2019-12-13 17:56:57 +01:00
#print(vis)
# if edge start and end node is the same
2019-12-06 10:45:47 +01:00
if -1 in vis:
print("TAK")
2019-12-13 17:56:57 +01:00
# if edge is in visited
elif -2 in vis:
print("TAK")
2019-12-06 10:45:47 +01:00
else:
print("NIE")