tricky nested list unpacking problem

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Dec 16 00:24:13 CET 2008


Arnaud Delobelle:
> Here is a not thought out solution:
>...

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.

def xflatten(seq):
    if isinstance(seq, list):
        stack = [iter(seq)]
        while stack:
            for item in stack[-1]:
                if isinstance(item, list):
                    stack.append(iter(item))
                    break
                yield item
            else:
                stack.pop()
    else:
        yield seq

def product(pools):
    if isinstance(pools, list):
        result = [[]]
        for pool in pools:
            if isinstance(pool, list):
                result = [x+[y] for x in result for y in xflatten(list
(product(pool)))]
            else:
                result = [x+[pool] for x in result]
        for prod in result:
            yield prod
    else:
        yield pools

s1 = [1,[2, 3, 4], 5,[6, 7]]
s2 = [1,[2, [3, 4]], 5,[6,7],8,[9]]
s3 = [1,2,3,[4,5,[6, 7]],8,[9,[10, 11, 12, 13, 14]]]

def stringify(seq):
    for el in product(seq):
        yield "0-" + "-".join(map(str, el))

for seq in [s1, s2, s3]:
    for txt in stringify(seq):
        print txt
    print

It's ugly, I agree.
No much tested.
*surely* there are shorter and much nicer solutions.
It reminds me the exercises of the "Little Schemer" :-)

Bye,
bearophile



More information about the Python-list mailing list