Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Permutations of n elements into r groups Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone have any ideas to help me?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading