-1

I have a list of numbers and I need all combinations without any member repeating its position in the list.

Example: If I have {1, 2, 3} then {3, 2, 1} is unacceptable because "2" is in the same position. The only good results are {3, 1, 2} and {2, 3, 1}. I need this on a larger scale, so far I have this:

import itertools
x = [1, 2, 3, 4, 5, 6, 7]
y = 5
comb = []
comb.extend(itertools.combinations(x,y))
print(comb)

This gives me all the combinations there are, but I need to eliminate those that have the same member at the same position, preferably not just when printing but in the comb list.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Lobsterguy
  • 93
  • 7
  • Provide expected output – Sociopath Nov 20 '18 at 07:18
  • I can't for the list provided in the code, but I did for the example where there are only 3 numbers in the list - [1,2,3], [3,1,2] and [2,3,1] as you can see in the text above. The point is that when the first combo is 1,2,3 then "1" can not be first in any other combination. The same goes for the other members of the list. – Lobsterguy Nov 20 '18 at 07:22

2 Answers2

1

From the expected output you've written, it seems you are looking for permutations rather than combinations

import itertools
import numpy as np
x = [1, 2, 3]
y = 3

no_repeat_permutations = []
for candidate_perm in itertools.permutations(x,y):
    for p in map(np.array, no_repeat_permutations):
        if any(np.array(candidate_perm) == p):
            break
    else:
        no_repeat_permutations.append(candidate_perm)

print(no_repeat_permutations)

>>> [(1, 2, 3), (2, 3, 1), (3, 1, 2)]

I am using numpy for element wise comparison, if any element-wise comparison in past results is True, we skip this permutations. In a case we don't find such comparison we enter the else statement and save the permutation.

For further explanation about for-else see this SO question

bluesummers
  • 11,365
  • 8
  • 72
  • 108
1

Not sure if I understood ... but maybe this is what you want ...

from collections import deque
from itertools import islice

def function(x, y):
    Q = deque(x)
    states = set()
    for _ in range(len(x)):
        states.add(tuple(islice(Q, 0, y)))
        Q.appendleft(Q.pop())
    return states

x = [1, 2, 3, 4, 5, 6, 7]
y = 5
resp = function(x, y)
print(resp)
>>> {(5, 6, 7, 1, 2), (1, 2, 3, 4, 5), (7, 1, 2, 3, 4), (2, 3, 4, 5, 6), (4, 5, 6, 7, 1), (6, 7, 1, 2, 3), (3, 4, 5, 6, 7)}
AResem
  • 139
  • 5