Getting all possible combinations of list items

Greg Krohn volucris at hotmail.com
Mon Sep 17 08:19:07 CEST 2001


Perfect! I doesn't even matter that I forgot to say that count is variable.
Thanks.

scratching my head over 'magic' code,
greg

--

Volucris (a) hotmail.com
"Eu não falo uma única palavra do português."

"Ignacio Vazquez-Abrams" <ignacio at openservices.net> wrote in message
news:mailman.1000706420.14634.python-list at python.org...
> On Mon, 17 Sep 2001, Greg Krohn wrote:
>
> > Does anyone know of how I should go about generating a list whose keys
are
> > all the possible combinations of the items in another list?
> > e.g.
> >
> > another_list = ['a', 'b', 'c']
> >
> > magic_algorithm(another_list) -> ['aa', 'ab', 'ac', 'ba', 'bc', 'bc',
'ca',
> > 'cb', 'cc']
> >
> > I know I could do this easily with nested 'fors', but that requires me
to
> > know the length of the set. Is this a case for recursive functions? I
hope
> > not, those things scare me. BTW, each item in another_list will be
unique,
> > if that matters.
>
> This solution treats the items in listin as values in a number system with
the
> radix equal to the number of items in the list and the number of positions
in
> count:
>
> ---
> def magic_algorithm(listin, count):
>   for i in listin:
>     if type(i)!=type(''):
>       raise TypeError, 'all items in list passed to magic_algorithm must
be strings'
>   l=len(listin)
>   return map(''.join, map(lambda x, count=count, l=l, listin=listin:
map(lambda y, x=x, count=count, l=l, listin=listin: listin[((x/(l**y)) %
l)], range(count)), xrange(l**count)))
> ---
>
> ---
> >>> magic_algorithm(['a', 'b', 'c'], 2)
> ['aa', 'ba', 'ca', 'ab', 'bb', 'cb', 'ac', 'bc', 'cc']
> >>>
> ---
>
> --
> Ignacio Vazquez-Abrams  <ignacio at openservices.net>
>
>





More information about the Python-list mailing list