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

Find combinations without changing order

I am trying to generate permutations from this list without changing the order.

mylist = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i"]]

The expected result:

acegi
bcehi
acfgi
bcfhi
adegi
bdehi
adfgi
bdfhi
acegi
bcehi
acfgi
bcfhi
adegi
bdehi
adfgi
bdfhi

This code is working as expected. But I will like to know if there is any other way.

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

for f in range(2):
    for s in range(2):
        for t in range(2):
            for f in range(2):
                print(
                    mylist[0][f]
                    + mylist[1][s]
                    + mylist[2][t]
                    + mylist[3][f]
                    + mylist[4][0]
                )

>Solution :

You can use itertools.product:

import itertools

mylist = [["a", "b"], ["c", "d"], ["e", "f"], ["g", "h"], ["i"]]

for p in itertools.product(*mylist):
    print(''.join(p))

# acegi
# acehi
# acfgi
# acfhi
# adegi
# adehi
# adfgi
# adfhi
# bcegi
# bcehi
# bcfgi
# bcfhi
# bdegi
# bdehi
# bdfgi
# bdfhi
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