Anas Rzq
Anas Rzq

Reputation: 93

find all possible combinations of list elements when moving ALL its elements everytime

I am trying to get the possible combinations of a list consists of 4 elements e.g: ('E', 'J', 'M', 'Z'), the condition to have for a valid combination is to change the positions of all 4 elements in every combination

Possible combinations are:

('J', 'E', 'Z', 'M')
('M', 'Z', 'E', 'J')
('Z', 'M', 'J', 'E').....

I tried itertools.permutations (('E', 'J', 'M', 'Z'), 4) and the results are not satisfactory at all. can someone help please?

Upvotes: 0

Views: 400

Answers (1)

Lenormju
Lenormju

Reputation: 4378

import itertools


def get_permutations_whose_all_elems_are_in_a_different_place_than_the_original(original_elems):
    for permutation in itertools.permutations(original_elems):
        if any(left == right for left, right in zip(permutation, original_elems)):
            continue
        else:
            yield permutation

initial_list = ('E', 'J', 'M', 'Z')
print(str(initial_list) + "\n--------------------")
solutions = get_permutations_whose_all_elems_are_in_a_different_place_than_the_original(initial_list)
print("\n".join(str(solution) for solution in solutions))

output :

('E', 'J', 'M', 'Z')
--------------------
('J', 'E', 'Z', 'M')
('J', 'M', 'Z', 'E')
('J', 'Z', 'E', 'M')
('M', 'E', 'Z', 'J')
('M', 'Z', 'E', 'J')
('M', 'Z', 'J', 'E')
('Z', 'E', 'J', 'M')
('Z', 'M', 'E', 'J')
('Z', 'M', 'J', 'E')

There is no E in the first column, no J in the second, no M in the third, no Z in the fourth.

Upvotes: 2

Related Questions