Home > OS >  find all n-long permutations (with repeats) of m-long list, n>m
find all n-long permutations (with repeats) of m-long list, n>m

Time:02-28

Say I have some list [0,1,2]. I then want return all n-long "permutations" of this list. For example, if n=5, I should have 3^5 choices enumerated:

[0,0,0,0,0]
[0,0,0,0,1]
[0,0,0,0,2]
[0,0,0,1,0]
...
[2,2,2,2,2]

I've been browsing for a post like this on stack overflow for a while and have tried many functions in the itertools library, including combinations, combinations_with_repeats, permutations, etc, but none of these will give me the output I desire. It's not hard to code myself, but I feel like a 5-fold nested loop will look very messy in my code, and I'd rather use an implementation in another library if it exists. I think I'm just searching in the wrong place. Thanks

CodePudding user response:

Python's itertools.product will do exactly what you need.

import sys
from itertools import product

DIGITS = (0, 1, 2)
N = int(sys.argv[1])

for tup in product(DIGITS, repeat = N):
    print(tup)

CodePudding user response:

You can also avoid the sort_list step. It was done just so that ordering looks like as in your original question. And used pandas df to make it look as is in your question.

lst = [0, 1, 2]
n = 5
def permutations(lst, n):
    if n == 0:
        return [[]]
    return [pre   [i] for i in lst for pre in permutations(lst, n - 1)]


# sort list of lists
def sort_list(lst):
    for i in range(len(lst)):
        lst[i].sort()
    return lst


import pandas as pd

print(pd.DataFrame(sort_list(permutations(lst, n))))
  • Related