combinations of variable length nested lists

Joseph A. Knapka jknapka at earthlink.net
Tue Aug 7 12:17:50 EDT 2001


David Lees wrote:
> 
> If your list is called
 'x' then len(x) will give you the number of
> sublists at the top level, which what you are asking for.

No, what he's asking for is: for a list N elements long,
N nested for loops over the elements of N (which are
themselves lists). Easy to do recursively:

# List we want combos of is the second argument.
def all_postfixes_of(ListSoFar,MoreLists,Result):
    if MoreLists == []:
        Result.append(ListSoFar)
        return
    next_list = MoreLists[0]
    for item in next_list:
        nextSoFar = ListSoFar[:]
        nextSoFar.append(item)
        all_postfixes_of(nextSoFar,MoreLists[1:],Result)

Result = []
all_postfixes_of([],[[1,2,3],[10,20],[4,5,6,7]],Result)
print Result

-- Joe
 
> david lees
> 
> Mark Robinson wrote:
> >
> > I have hurt my brain (and those who are unfortunate to sit near me ;))
> > trying to formulate an algorithm for the following problem. I am sure
> > that someone here must be able to help me out, it seems such a trivial
> > problem.
> >
> > I have a nested list structure of the following format:
> > [[2, 3, 4, 5],
> >   [4, 5, 6, 7, 34],
> >   [6, 2, 7, 4]
> >   ....
> >   ....
> > ]
> >
> > I want to generate all possible combinations that take one element from
> > each nested list
> >
> > i.e
> > [2, 4, 6, ..., ...]
> > [2, 4, 2, ..., ...]
> >
> > If I knew the length of the outermost list beforehand I could hard code
> > it as a series of nested for loops:
> >
> > i.e
> >
> > for i in list[0]:
> >         for j in list[1]:
> >                 for k in list[2]:
> >                                 comb = [i, j, k]
> >
> > but I can't figure a way to do this dynamically at runtime, when the
> > outermost list is going to be variable in length.
> >
> > If anyone can help, I'll be willing to sell my boss into slavery and
> > give you all the profit ;)
> >
> > Blobby

-- Joe Knapka
"You know how many remote castles there are along the gorges? You
 can't MOVE for remote castles!" -- Lu Tze re. Uberwald
// Linux MM Documentation in progress:
// http://home.earthlink.net/~jknapka/linux-mm/vmoutline.html
2nd Lbl A + 1 = 2nd Pause 2nd Prt GTO 2 R/S



More information about the Python-list mailing list