Generating all combinations

Mensanator mensanator at aol.com
Mon Jun 1 14:23:35 EDT 2009


On Jun 1, 10:11 am, pataphor <patap... at gmail.com> wrote:
> Johannes Bauer wrote:
> > Any help is appreciated!
>
> This is on the fringe of exploitation, but hey, maybe the code helps you
> think about the algorithm.
>
> IMHO the following code is a glaring complaint about the injustice of
> omission itertools inflicts on the perfectly natural and obvious
> procedure of repeat_each (whatever it's name ought to be):

I believe the name you're looking for is
combinations_with_replacement.
It is one of the features being added to 3.1 which should give all
the subsets of the Cartesian Product:

permutations_with_replacement:    product()
combinations_with_replacement:    combinations_with_replacement()
permutations_without_replacement: permutations()
combinations_without_replacement: combinations()

>
> from itertools  import izip, islice, cycle
>
> def repeat_each(seq,n):
>      while True:
>          for x in seq:
>              for i in range(n):
>                  yield x
>
> def repeat_all(seq,n):
>      while True:
>          for i in range(n):
>              for x in seq:
>                  yield x
>
> def product(X):
>      N = []
>      total = 1
>      for x in X:
>          N.append(total)
>          total *= len(x)
>      R = [repeat_all(repeat_each(x,k),n)
>                      for x,k,n in izip(X,N,reversed(N))]
>      return islice(izip(*R),total)
>
> def test1():
>      L = ['a', 'bc','def' ]
>      for x in product(L):
>          print x
>      print
>
> def test2():
>      repeat_all = cycle
>      test1()
>
> if __name__ == '__main__':
>      test1()
>      test2()
>
> See? Repeat_all and repeat_each are almost brothers, just separated by
> the tiniest rearrangement of their genetic code (or should I say code
> genetics?). Yet one is included as 'itertools.cycle' and the other is
> doomed to live in limbo. Such injustice! Can it be that
> 'itertools.repeat' has usurped repeat_each's rightful position?
>
> P.




More information about the Python-list mailing list