Can anyone solve this?

Thomas Sicheritz-Ponten thomas at cbs.dtu.dk
Wed Jun 28 03:52:20 EDT 2000


Matthew Schinckel <matt at null.net> writes:

> <rdudfield at my-deja.com> wrote in message
> news:<8j737m$t5a$1 at nnrp1.deja.com>...
> > Hi,
> > 
> > I've got a problem here which I just can't figure out.
> > 
> > a = [1,2,3] b = ["c",32] c = [1,2]
> > 
> > inputlist = [a,b,c]
> > 
> > Inputlist can have any number of lists in it. The lists in it can have
> > any number of elements in them.
> > 
> > I need the code to give every possible combination of the lists in
> > inputlist.
> > 
> > This is what the answer should be for the inputlist above.
> > 
> > outputlist = [[1, 'c', 1], [1, 'c', 2], [1, 32, 1], [1, 32, 2], [2,
> > 'c', 1], [2, 'c', 2], [2, 32, 1], [2, 32, 2], [3, 'c', 1], [3, 'c',
> > 2], [3, 32, 1], [3, 32, 2]] []
> 
> I did find something about combinatorics on starship yesterday, but I
> can't remember where it was.

something I found on dejanews a couple of months ago ...

def cartesian(listList):
    if listList:
        result = []
        prod = cartesian(listList[:-1])
        for x in prod:
            for y in listList[-1]:
                result.append(x + (y,))
        return result
    return [()]

a = [1,2,3]
b = ["c",32]
c = [1,2]

inputlist = [a,b,c]

print cartesian(inputlist)

[(1, 'c', 1), (1, 'c', 2), (1, 32, 1), (1, 32, 2), (2, 'c', 1), (2, 'c',
2), (2, 32, 1), (2, 32, 2), (3, 'c', 1), (3, 'c', 2), (3, 32, 1), (3, 32,
2)]




More information about the Python-list mailing list