-2

I have a list [1, 2, 3]. I want a function that takes in the list and another number, the length.

f([1, 2, 3], 4) = [
[1, 1, 1, 1],
[1, 1 , 1, 2],
[1, 1, 1, 3],
[1, 1, 2, 1],
[1, 1, 3, 1],
#and so on...
]

Maybe itertools has an answer?

Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38

1 Answers1

6

itertools.combinations_with_replacement is the function you seek.

In [17]: i=itertools.combinations_with_replacement((1,2,3), 4)

In [18]: next(i)
Out[18]: (1, 1, 1, 1)

In [19]: next(i)
Out[19]: (1, 1, 1, 2)

In [20]: next(i)
Out[20]: (1, 1, 1, 3)

In [21]: next(i)
Out[21]: (1, 1, 2, 2)

In [22]: 

If you want the set of all combinations, including items which differ only in order, try this:

# Modified from itertools.combinations_with_replace example
# from the python doc.
import itertools
import pprint
def odometer(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in itertools.product(range(n), repeat=r):
        yield tuple(pool[i] for i in indices)

pprint.pprint (list(odometer([1,2,3], 4)))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308