-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patheularian.py
More file actions
70 lines (58 loc) · 1.94 KB
/
eularian.py
File metadata and controls
70 lines (58 loc) · 1.94 KB
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
# Definitions:
# Eularian path - Path that visited every edge exactly once.
# Eularian circuit - Eularian path that starts and ends at the same vertex.
# How to identify?
# Identify add connected components
# Total no. of odd degree vertices can't never be odd.
# Find all the connected vertices and check if:
# 1. Total odd degree vertices more than 2: None
# 2. 2 odd degree vertices - Path.
# 4. 0 odd degree vertices - Circuit
#
#
# Extra knowledge - Hamoltian Path is a path that visits every vertex exactly once.
# Likewise for hamoltian circuit, the source and destination vertex should match.
# There is no way to identify if graph has hamoltian path. Moreover, this forms the
# base question for Travelling salesman problem, such that the weights in minimal.
def eularian(adj_list):
odd_count = 0
for vertice in adj_list:
if adj_list[vertice] and len(adj_list[vertice]) & 1:
odd_count += 1
if odd_count == 0:
return "Circuit"
elif odd_count == 2:
return "Path"
else:
return "None"
if __name__ == '__main__':
# None
adj_list = {
'U': {'V': 2, 'W': 5, 'X': 1},
'V': {'U': 2, 'X': 2, 'W': 3},
'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5},
'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1},
'Y': {'X': 1, 'W': 1, 'Z': 1},
'Z': {'W': 5, 'Y': 1},
}
print(eularian(adj_list))
# Path
adj_list = {
'U': {'W': 5, 'X': 1},
'V': {'X': 2, 'W': 3},
'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5},
'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1},
'Y': {'X': 1, 'W': 1, 'Z': 1},
'Z': {'W': 5, 'Y': 1},
}
print(eularian(adj_list))
# Path
adj_list = {
'U': {'W': 5, 'X': 1},
'V': {'X': 2, 'W': 3},
'W': {'V': 3, 'U': 5, 'X': 3, 'Z': 5},
'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1},
'Y': {'X': 1, 'Z': 1},
'Z': {'W': 5, 'Y': 1},
}
print(eularian(adj_list))