回答編集履歴
1
追記
answer
CHANGED
@@ -1,3 +1,34 @@
|
|
1
|
+
(追記)
|
2
|
+
もっと素直に組んでみました
|
3
|
+
```python
|
4
|
+
def unify_group2(all_groups: List[Set[int]]) -> List[Set[int]]:
|
5
|
+
val_to_index = {}
|
6
|
+
result = []
|
7
|
+
|
8
|
+
for s in all_groups:
|
9
|
+
indices = {val_to_index.get(n, -1) for n in s}
|
10
|
+
if max(indices) == -1:
|
11
|
+
result.append(s)
|
12
|
+
index = len(result) - 1
|
13
|
+
for n in s:
|
14
|
+
val_to_index[n] = index
|
15
|
+
else:
|
16
|
+
indices = sorted(i for i in indices if i > -1)
|
17
|
+
index = indices[0]
|
18
|
+
for i in indices[1:]:
|
19
|
+
result[index] |= result[i]
|
20
|
+
for j in result[i]:
|
21
|
+
val_to_index[j] = index
|
22
|
+
# 空をセットしておいて後で取り除く
|
23
|
+
result[i] = {}
|
24
|
+
result[index] |= s
|
25
|
+
for n in s:
|
26
|
+
val_to_index[n] = index
|
27
|
+
|
28
|
+
return list(filter(None, result))
|
29
|
+
```
|
30
|
+
----
|
31
|
+
|
1
32
|
私だったら……
|
2
33
|
```python
|
3
34
|
from typing import Dict, List, Set
|