Home > front end >  Permutations of n elements into r groups Python
Permutations of n elements into r groups Python

Time:12-27

I don't know how to create an algorithm / which to use for the following problem:

If I have a set of 20 elements (e.g. A -> T) and have a string of length 8, what are the permutations I could make? (I know there's around 390 million)

e.g. we could have ABCDEFGH or EFHGATRI.

Does anyone have any ideas to help me?

CodePudding user response:

If you want all permutations, given the number of possibilities, better keep it as a generator. For this, use itertools.permutations:

from itertools import permutations
from string import ascii_uppercase

letters = ascii_uppercase[:20]

perms = map(''.join, permutations(letters, r=8))  # this doesn't generate
                                                  # anything yet

# then use it lazily

for p in perms:
    # do something


# or get elements one by one
next(perm)

If you only want random possibilities, use random.sample:

from random import sample
from string import ascii_uppercase

''.join(sample(ascii_uppercase[:20], 8))

example output: 'IKEDQRTS'

CodePudding user response:

Python has specific function for your issue itertools.permutations

Return successive r length permutations of elements in the iterable.

So, you can use it for your task

["".join(x) for x in itertools.permutations("abcd", 3)]
> ['abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

Also, you can use generators to reduce RAM usage

def perms():
    for perm in itertools.permutations("abcdefghij", 5):
        yield "".join(perm)

for p in perms():
    print(p)
  • Related