1

Consider the following code:

list_example = [1,2,3,4,5,6,7,8,9]
List_of_ball_permutations = []

    for i in list_example :
       for j in list_example:
           if j>i:
               List_of_ball_permutations.append([i,j])

This will result in a list being formed as follows:

[[1, 2],
 [1, 3],
 [1, 4],
 [1, 5],
 [1, 6],
 [1, 7],
 [1, 8],
 [1, 9],
 [2, 3],
 [2, 4],
 [2, 5],
 [2, 6],
 [2, 7],
 [2, 8],
 [2, 9],
 [3, 4],
 [3, 5],
 [3, 6],
 [3, 7],
 [3, 8],
 [3, 9],
 [4, 5],
 [4, 6],
 [4, 7],
 [4, 8],
 [4, 9],
 [5, 6],
 [5, 7],
 [5, 8],
 [5, 9],
 [6, 7],
 [6, 8],
 [6, 9],
 [7, 8],
 [7, 9],
 [8, 9]]             

Whereby each number is paired with another number in the list and no repeats i.e. if [1,2] exists then [2,1] will not be created also pairs with two of the same numbers e.g. [1,1] will not be created either.

However now consider a list of objects whereby I would like to pair each object with one other object (not itself and no repeats) in a similar fashion as the numbers were. For some reason my code does not allow me to do that as it presents a message '>' not supported between instances of 'Ball' and 'Ball'. (The class I created was called Ball which generated the objects).

Any help to resolve this issue would be very much appreciated.

DJA
  • 173
  • 6
  • Read about `itertools.combinations` – Michael Butscher Nov 29 '17 at 03:18
  • 1
    @MichaelButscher not permutations, [combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations) ;) e.g. `list(combinations(["a", "b", "c"], 2))` – Nir Alfasi Nov 29 '17 at 03:19
  • @alfasin Right, thanks. – Michael Butscher Nov 29 '17 at 03:20
  • Possible duplicate of [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Nir Alfasi Nov 29 '17 at 03:25
  • `List_of_ball_permutations = [list(x) for x in itertools.combinations(list_example, 2)]` or `List_of_ball_permutations = list(map(list, itertools.combinations(list_example, 2)))` – RoadRunner Nov 29 '17 at 03:30

1 Answers1

2

Of course, itertools is the proper "pythonic" solution:

import itertools
list(itertools.combinations(["a", "b", "c"], 2))

However, you have the correct idea, you can generate all the indices of the objects to be paired, and retrieve them:

def get_pairs(n):
    for i in range(n) :
        for j in range(i+1, n):
            yield (i, j)

def get_objects_pairs(objects):
    for first, second in get_pairs(len(objects)):
        yield objects[first], objects[second]

objects = ['a', 'ball', 'toothbrush']
for pair in (get_objects_pairs(objects)):
    print(pair)

output:

('a', 'ball')
('a', 'toothbrush')
('ball', 'toothbrush')
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80