Pythonic idioms / Programming Puzzle

Lloyd Goldwasser goldwasser at demog.berkeley.edu
Tue Jan 22 18:28:07 EST 2002


ameoba wrote:
> [...] permutations of an arbitrary list of arbitrarily long lists of strings.
> 
> in 4 lines.

Here's a slightly different solution, one that puts the combinations*
into lists rather than strings, which may have a wider applicability. 
It avoids explicitly building up a results string from [], at the
expense of doing a length test:


def choices(menulist):
    if len(menulist)>1:
        return [[x]+y for x in menulist[0] for y in
choices(menulist[1:])]
    else:
        return [[x] for x in menulist[0]]


and here's another one, not wildly different from Jason's
string-oriented solution:


def choices(menulist):
    return reduce(lambda L1,L2: [x+[y] for x in L1 for y in L2],
                  menulist[1:], [[x] for x in menulist[0]])


(Both fail, though, if menulist is empty.)


Lloyd


* On a really pedantic note: "permutations" are changes in the order of
a fixed set of elements (e.g., [a,b,c] -> [[a,b,c], [a,c,b], [b,a,c],
[b,c,a], [c,a,b], [c,b,a]]).  If I understand the question, we're
talking "combinations" (taking one from list1, one from list2, and so
on).


-- 
Lloyd Goldwasser                                Department of Demography
goldwasser at demog.berkeley.edu                   2232 Piedmont Ave. #2120
(510) 642-0525                                  University of California
fax: (510) 643-8558                             Berkeley, CA  94720-2120



More information about the Python-list mailing list