-
Notifications
You must be signed in to change notification settings - Fork 892
/
problem_207.py
61 lines (50 loc) · 1.39 KB
/
problem_207.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
class Node:
def __init__(self, val):
self.val = val
def __repr__(self):
return str(self.val)
class Graph:
def __init__(self):
self.nodes, self.edges = set(), dict()
self.set_1, self.set_2 = set(), set()
def is_bipartite(self):
sorted_nodes = sorted(self.edges.items(),
key=lambda x: len(x[1]), reverse=True)
for node, _ in sorted_nodes:
if node in self.set_2:
continue
self.set_1.add(node)
if self.edges[node]:
for other_node in self.edges[node]:
self.set_2.add(other_node)
for node in self.set_2:
if self.edges[node]:
for other_node in self.edges[node]:
if other_node in self.set_2:
return False
return True
# Tests
g = Graph()
a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')
f = Node('f')
g.nodes = set([a, b, c, d, e, f])
g.edges[a] = set([d])
g.edges[b] = set([d, e, f])
g.edges[c] = set([f])
g.edges[d] = set([a, b])
g.edges[e] = set([b])
g.edges[f] = set([b, c])
assert g.is_bipartite()
g.edges = dict()
g.nodes = set([a, b, c, d, e, f])
g.edges[a] = set([d])
g.edges[b] = set([d, e, f])
g.edges[c] = set([f])
g.edges[d] = set([a, b])
g.edges[e] = set([b, f])
g.edges[f] = set([b, c, e])
assert not g.is_bipartite()