Skip to content
Advertisement

How to print each possible permutation of several arrays of strings on Python?

Let’s say I have the following arrays of strings:

Background = {"Ocean"}
Body = {"Normal"}
Eyes = {"Big", "Small", "Monolid"}
Color = {"Yellow", "White", "Red Rose", "Turquoise", "Dark green", "Orange"}
Hands = {"None", "Robot", "Spider", "Bear"}
Extra = {"Empty", "Sand", "Dust", "Graffiti", "Aloe"}

I want to print a list that contains all possible permutations of each element mentioned in the arrays above, following the order in which these arrays were set (i.e. it starts checking on Background, then goes to check Body, then Eyes, then Color, then Hands, and finishes on Extra).

The first permutation should be:

1. Ocean, Normal, Big, Yellow, None, Empty

The second permutation should be:

2. Ocean, Normal, Big, Yellow, None, Sand

And so on…

It can be assumed that the item None is the same as Empty.

How could I do that?

Advertisement

Answer

The following solution should work Assume arrays are as follows

Backgrounds = ["Ocean"]
Bodys = ["Normal"]
Eyes = ["Big", "Small", "Monolid"]
Colors = ["Yellow", "White", "Red Rose", "Turquoise", "Dark green", "Orange"]
Hands = ["None", "Robot", "Spider", "Bear"]
Extra = ["Empty", "Sand", "Dust", "Graffiti", "Aloe"]
for background in Backgrounds:
    for body in Bodys:
       for eye in Eyes:
           for colour in colours:
                 for hand in Hands:
                      for extra in extras:
                             print(background,body,eye,colour,hand,extra)

If your lists are really large please don’t use the above solution because its time complexity is o(n^6).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement