tricky nested list unpacking problem

Arnaud Delobelle arnodel at googlemail.com
Tue Dec 16 05:15:08 EST 2008


bearophileHUGS at lycos.com writes:

> I was waiting to answer because so far I have found a bad-looking
> solution only. Seeing there's only your solution, I show mine too. It
> seems similar to your one.

I think that the solution below is a bit clearer, although I think it is
more resource intensive than my first one.  I've switched to a generator
function to make it more easily comparable.  It's true that it's a
problem that seems designed for Scheme!

l1 = [1,2,3,[5,6]]
l2 = [1,2,3,[5,6],[7,8,9]]
l3 = [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]

def flatten(x):
    if isinstance(x, list):
        for y in x:
            for z in flatten(y):
                yield z
    else:
        yield x

def unpack(lst, acc=[]):
    i = len(acc)
    if i == len(lst):
        yield '-'.join(map(str, acc))
    else:
        for x in flatten(lst[i]):
            for res in unpack(lst, acc + [x]):
                yield res

-- 
Arnaud



More information about the Python-list mailing list