views:

78

answers:

1

What is the fastest way to solve the following I will to join several lists based on common head or tail

input = ([5,6,7], [1,2,3], [3,4,5], [8, 9])
output = [1, 2, 3, 4, 5, 6, 7]
+1  A: 
>>> def chain(inp):
    d = {}
    for i in inp:
        d[i[0]] = i[:], i[-1]
    l, n = d.pop(min(d))
    while True:
        lt, n = d.pop(n, [None, None])
        if n is None:
            if len(d) == len(inp) - 1:
                l, n = d.pop(min(d))
                continue
            break
        l += lt[1:]
    return l

>>> chain(input)
[1, 2, 3, 4, 5, 6, 7]
>>> chain(([5,6,7], [1,2,10], [3,4,5], [8, 9]))
[3, 4, 5, 6, 7]
SilentGhost
Thanks SilentGhost. It's general enough (str and int) and works perfectly. Are there any general name for this type of method. I call it 'tiling list'
Joey
may be http://en.wikipedia.org/wiki/Linked_list ?
SilentGhost
input = ([5,6,7], [1,2,3], [3,4,5], [8, 9], [9, 10, 11], [12])output = ([1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11])is recursion a good idea for this case?
Joey
input = ([5,6,7], [1,2,10], [3,4,5], [8, 9])output = [3, 4, 5, 6, 7]Oeps! the previous won't work if given the above input
Joey
given the above input, you just need to check `d` and run my code again, therefore obtaining `[8,9,10,11]` list. in your second example you could do the same, but it's not clear on what ground would you have excluded `[1, 2, 10]` and `[8,9]` lists.
SilentGhost
[3,4,5] and [5,6,7] are joining because [3,4,5] has a tail 5 and [5,6,7] have a head 5.
Joey
@Joey: updated the code
SilentGhost