Getting all possible combinations of list items

Ignacio Vazquez-Abrams ignacio at openservices.net
Mon Sep 17 01:59:36 EDT 2001


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