1 testdata = "c/3 a b d b/1 c/1 c/2/x c/2 c".split(" ")
3 def strategy_byearlychild(sequence):
4 """Sort by earliest child
6 When this strategy is used, a parent is displayed with all its children as
7 soon as the first child is supposed to be shown.
9 >>> strategy_byearlychild(testdata)
10 ['c', 'c/3', 'c/1', 'c/2', 'c/2/x', 'a', 'b', 'b/1', 'd']
13 # first step: pull parents to top
14 def firstchildindex(item):
15 childindices = [i for (i,text) in enumerate(sequence) if text.startswith(item + "/")]
16 # distinction required as min(foo, *[]) tries to iterate over foo
18 return min(sequence.index(item), *childindices)
20 return sequence.index(item)
21 sequence = sorted(sequence, key=firstchildindex)
23 # second step: pull other children to the start too
24 return strategy_byparents(sequence)
26 def strategy_byparents(sequence):
27 """Sort by parents only
29 With this strategy, children are sorted *under* their parents regardless of
30 their own position, and the parents' positions are determined only by
31 comparing the parents themselves.
33 >>> strategy_byparents(testdata)
34 ['a', 'b', 'b/1', 'd', 'c', 'c/3', 'c/1', 'c/2', 'c/2/x']
37 def partindices(item):
38 """Convert an entry a tuple of the indices of the entry's parts.
40 >>> sequence = testsequence
41 >>> assert partindices("c/2/x") == (sequence.index("c"), sequence.index("c/2"), sequence.index("c/2/x"))
43 return tuple(sequence.index(item.rsplit('/', i)[0]) for i in range(item.count('/'), -1, -1))
45 return sorted(sequence, key=partindices)
47 def strategy_forcedsequence(sequence):
48 """Forced Sequence Mode
50 Using this strategy, all entries will be shown in the sequence; this can
51 cause parents to show up multiple times.
53 The only reason why this is not the identical function is that parents that
54 are sorted between their children are bubbled up to the top of their
55 contiguous children to avoid being repeated in the output.
57 >>> strategy_forcedsequence(testdata)
58 ['c/3', 'a', 'b', 'd', 'b/1', 'c', 'c/1', 'c/2', 'c/2/x']
61 # this is a classical bubblesort. other algorithms wouldn't work because
62 # they'd compare non-adjacent entries and move the parents before remote
63 # children. python's timsort seems to work too...
65 for i in range(len(sequence), 1, -1):
67 if sequence[j-1].startswith(sequence[j] + '/'):
68 sequence[j-1:j+1] = [sequence[j], sequence[j-1]]
72 def strategy_forcedsequence_timsort(sequence):
73 sequence.sort(lambda x,y: -1 if y.startswith(x) else 1)
76 if __name__ == "__main__":
82 for perm in itertools.permutations(testdata):
83 if strategy_forcedsequence(testdata[:]) != strategy_forcedsequence_timsort(testdata[:]):
84 print "difference for testdata", testdata
85 print "normal", strategy_forcedsequence(testdata[:])
86 print "timsort", strategy_forcedsequence_timsort(testdata[:])