Taylor08 Taylor08 -3 years ago 91
Python Question

Generate more random combination with a list of string

I created a variable list like this :

Code = ["RIGHT_ARROW","DOWN_ARROW","LEFT_ARROW","UP_ARROW"]


I would like to generate more combination of my list like this :

newCode = ["RIGHT_ARROW","DOWN_ARROW","LEFT_ARROW","UP_ARROW"]


or

["UP_ARROW","RIGHT_ARROW","DOWN_ARROW","LEFT_ARROW"]


or

["LEFT_ARROW","UP_ARROW","RIGHT_ARROW","DOWN_ARROW"]`


or

["DOWN_ARROW","LEFT_ARROW","UP_ARROW","RIGHT_ARROW"]`


...etc

Is it possible to generate all combinations to the new list?

I tested by
itertools.permumations
or combinations but this result isn't what I want.

Any ideas?

Answer Source

You can try this way :

def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                # nb elements[0:1] works in both string and list contexts
                yield perm[:i] + elements[0:1] + perm[i:]

Code = ["RIGHT_ARROW", "DOWN_ARROW", "LEFT_ARROW", "UP_ARROW"]
print(*all_perms(Code))

Output :

['RIGHT_ARROW', 'DOWN_ARROW', 'LEFT_ARROW', 'UP_ARROW'] ['DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW', 'UP_ARROW'] ['DOWN_ARROW', 'LEFT_ARROW', 'RIGHT_ARROW', 'UP_ARROW'] ['DOWN_ARROW', 'LEFT_ARROW', 'UP_ARROW', 'RIGHT_ARROW'] ['RIGHT_ARROW', 'LEFT_ARROW', 'DOWN_ARROW', 'UP_ARROW'] ['LEFT_ARROW', 'RIGHT_ARROW', 'DOWN_ARROW', 'UP_ARROW'] ['LEFT_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'UP_ARROW'] ['LEFT_ARROW', 'DOWN_ARROW', 'UP_ARROW', 'RIGHT_ARROW'] ['RIGHT_ARROW', 'LEFT_ARROW', 'UP_ARROW', 'DOWN_ARROW'] ['LEFT_ARROW', 'RIGHT_ARROW', 'UP_ARROW', 'DOWN_ARROW'] ['LEFT_ARROW', 'UP_ARROW', 'RIGHT_ARROW', 'DOWN_ARROW'] ['LEFT_ARROW', 'UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW'] ['RIGHT_ARROW', 'DOWN_ARROW', 'UP_ARROW', 'LEFT_ARROW'] ['DOWN_ARROW', 'RIGHT_ARROW', 'UP_ARROW', 'LEFT_ARROW'] ['DOWN_ARROW', 'UP_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW'] ['DOWN_ARROW', 'UP_ARROW', 'LEFT_ARROW', 'RIGHT_ARROW'] ['RIGHT_ARROW', 'UP_ARROW', 'DOWN_ARROW', 'LEFT_ARROW'] ['UP_ARROW', 'RIGHT_ARROW', 'DOWN_ARROW', 'LEFT_ARROW'] ['UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW'] ['UP_ARROW', 'DOWN_ARROW', 'LEFT_ARROW', 'RIGHT_ARROW'] ['RIGHT_ARROW', 'UP_ARROW', 'LEFT_ARROW', 'DOWN_ARROW'] ['UP_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW', 'DOWN_ARROW'] ['UP_ARROW', 'LEFT_ARROW', 'RIGHT_ARROW', 'DOWN_ARROW'] ['UP_ARROW', 'LEFT_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download