house_of_graphs.edges_iter()   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 11
rs 9.3333
c 0
b 0
f 0
cc 5
nop 1
1
from collections.abc import Iterable, Mapping
2
from pprint import pprint
3
from typing import Union
4
5
import networkx as nx
6
7
8
def parse(adjacency_list: str) -> Iterable[tuple[int, list[int]]]:
9
    for line in adjacency_list.strip().splitlines():
10
        s, tl = line.split(":")
11
        yield int(s), [int(t) for t in tl.strip().split()]
12
13
14
def adjacency_mapping(adjacency_list: str) -> Mapping[int, list[int]]:
15
    return dict(parse(adjacency_list))
16
17
18
def edges_iter(adjacency_source: Union[str, Mapping[int, list[int]]]) -> Iterable[tuple[int, int]]:
19
    if isinstance(adjacency_source, str):
20
        adjacency_list = parse(adjacency_source)
21
    elif isinstance(adjacency_source, Mapping):
22
        adjacency_list = adjacency_source.items()
23
    else:
24
        raise TypeError("'adjacency_source' should be a 'str' or a Mapping[int, list[int]]")
25
26
    for s, tl in adjacency_list:
27
        for t in tl:
28
            yield int(s), int(t)
29
30
31
def graph(adjacency_source: Union[str, Mapping[int, list[int]]]) -> nx.Graph():
32
    return nx.Graph(list(edges_iter(adjacency_source)))
33
34
35
if __name__ == '__main__':
36
    a = """
37
1: 4 15
38
2: 8 17
39
3: 8 17
40
4: 1 14
41
5: 7 14
42
6: 7 14
43
7: 5 6
44
8: 2 3
45
9: 11 16
46
10: 13 15
47
11: 9 12
48
12: 11 16 17
49
13: 10 16 17
50
14: 4 5 6 15
51
15: 1 10 14 16
52
16: 9 12 13 15
53
17: 2 3 12 13
54
    """
55
56
    m = adjacency_mapping(a)
57
58
    pprint(m)
59