File size: 2,278 Bytes
ab4488b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Utilities."""


def commonancestors(*nodes):
    """
    Determine common ancestors of `nodes`.

    >>> from anytree import Node, util
    >>> udo = Node("Udo")
    >>> marc = Node("Marc", parent=udo)
    >>> lian = Node("Lian", parent=marc)
    >>> dan = Node("Dan", parent=udo)
    >>> jet = Node("Jet", parent=dan)
    >>> jan = Node("Jan", parent=dan)
    >>> joe = Node("Joe", parent=dan)

    >>> util.commonancestors(jet, joe)
    (Node('/Udo'), Node('/Udo/Dan'))
    >>> util.commonancestors(jet, marc)
    (Node('/Udo'),)
    >>> util.commonancestors(jet)
    (Node('/Udo'), Node('/Udo/Dan'))
    >>> util.commonancestors()
    ()
    """
    ancestors = [node.ancestors for node in nodes]
    common = []
    for parentnodes in zip(*ancestors):
        parentnode = parentnodes[0]
        if all(parentnode is p for p in parentnodes[1:]):
            common.append(parentnode)
        else:
            break
    return tuple(common)


def leftsibling(node):
    """
    Return Left Sibling of `node`.

    >>> from anytree import Node, util
    >>> dan = Node("Dan")
    >>> jet = Node("Jet", parent=dan)
    >>> jan = Node("Jan", parent=dan)
    >>> joe = Node("Joe", parent=dan)
    >>> print(util.leftsibling(dan))
    None
    >>> print(util.leftsibling(jet))
    None
    >>> print(util.leftsibling(jan))
    Node('/Dan/Jet')
    >>> print(util.leftsibling(joe))
    Node('/Dan/Jan')
    """
    if node.parent:
        pchildren = node.parent.children
        idx = pchildren.index(node)
        if idx:
            return pchildren[idx - 1]
    return None


def rightsibling(node):
    """
    Return Right Sibling of `node`.

    >>> from anytree import Node, util
    >>> dan = Node("Dan")
    >>> jet = Node("Jet", parent=dan)
    >>> jan = Node("Jan", parent=dan)
    >>> joe = Node("Joe", parent=dan)
    >>> print(util.rightsibling(dan))
    None
    >>> print(util.rightsibling(jet))
    Node('/Dan/Jan')
    >>> print(util.rightsibling(jan))
    Node('/Dan/Joe')
    >>> print(util.rightsibling(joe))
    None
    """
    if node.parent:
        pchildren = node.parent.children
        idx = pchildren.index(node)
        try:
            return pchildren[idx + 1]
        except IndexError:
            return None
    else:
        return None