-
Notifications
You must be signed in to change notification settings - Fork 2
/
BA3_G - Eulerian Path in Digraph.py
95 lines (71 loc) · 2.14 KB
/
BA3_G - Eulerian Path in Digraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 22:56:56 2019
@author: jasonmoggridge
http://rosalind.info/problems/ba3g/
BA3_G:
Eularian path in digraph
"""
import sys
sys.setrecursionlimit(10**6)
"""Find the source node to initiate dfs at:"""
def get_source(Adj):
deg = {}
for v in Adj:
if v not in deg.keys():
deg[v] = -len(Adj[v])
else:
deg[v] -= len(Adj[v])
for u in Adj[v]:
if u not in deg.keys():
deg[u] = 1
else:
deg[u] += 1
for v in deg:
if deg[v] == -1:
source = v
return source
"""Eularian path/circuit dfs"""
def dfs(v, graph, path, stack):
print('dfs: v:',v,'\nPath:',path,'\nStack:',stack)
if v not in graph.keys():
print('\thit the sink')
path.append(v)
if len(stack) == 0:
print('\t\tNo stack left\n\t\tPath is:', path)
return
else:
print('\t\tStill stack >>>', stack[-1])
dfs(stack.pop(), graph, path, stack)
elif len(graph[v]) == 0:
print('\tNo neighbors')
path.append(v)
if len(stack) == 0:
print('\t\tNo stack left\n\t\tPath is:', path)
return
else:
print('\t\tStill stack >>>', stack[-1])
dfs(stack.pop(), graph, path, stack)
else:
print('\t Going deeper, appending stack, going to :', graph[v][0])
stack.append(v)
dfs(graph[v].pop(0), graph, path, stack)
###
f = open('//Users/jasonmoggridge/Desktop/rosalind_ba3g.txt', 'r')
lines = list(str(l.strip('\n')) for l in f.readlines())
Edges = [[i.strip(' ') for i in line.split('->')] for line in lines]
Adj = {}
for edge in Edges:
Adj[int(edge[0])]=[int(i) for i in edge[1].split(',')]
del((Edges, lines, f))
source = get_source(Adj)
stack = []
path = []
dfs(source, Adj, path, stack)
path.reverse()
string = '->'.join(str(i) for i in path)
#print('\n\n\n',string)
with open('//Users/jasonmoggridge/Desktop/rosalind_ba3g_output.txt', 'w') as wr:
wr.write(string)
wr.close()