Sorting a list of tuples such that grouping by key is not desired

Viewed 160

I have a list of IDs that represent users, and I'm writing a function to turn that list of IDs into a schedule of user matchups (pairings) like so:

ids = [1, 2, 3, 4]

The schedule related to this would look like:

week 1: (1, 2), (3, 4)
week 2: (1, 3), (2, 4)
week 3: (1, 4), (2, 3)
week 4: (1, 2), (3, 4) [repeat of week 1]

and so on. I was trying to do this with nested for loops based on the number of user IDs and the combinations resulting from that.

ids = [1,2,3,4]
matchups = []

#generate all the combinations of matchups
for subset in itertools.combinations(ids,2):
    matchups.append(subset)

This returns all the potential pairings as a list of tuples- great! That's the core of what I'm looking for. My issue now has been figuring out how to transform this into something useable. For example, the above code returns this list for matchups:

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

I was trying a complicated recursive function to build a list of the unique pairings for each week, then I realized that if I have the above list in the right order, I can simply use it to assign pairings from start to finish, regardless of week, and repeating when I reach the end. That is, I can just assign pairings to weeks using the known number of pairings needed per week and the known number of weeks.

To that end, I've been trying to figure out how to sort a list of tuples based on elements that are not equal. The sorted() method has many useful implementations this type of situation, but I can only get results where like results are grouped, such as the above.

I'd like to find a use of sorted() that will return the following, almost like an anti-sort:

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

Is there a way to use lambda for this?

EDIT: I just realized that the 1st element needs to be paired with the 6th, 2nd with 5th, and 3rd with 4th. I don't know if this extends to the general case, but I expect its possible, because I've taken other steps to ensure there are always an even number of IDs.

Now I'm sure there's some way to interpolate the list to achieve this.

EDIT2: Looks like the previous hunch wasn't correct- it doesn't work with 6 IDs, and likely anything beyond that would fail too. I'm back to trying to figure out if there's a way to disperse instead of sort based on a key

4 Answers
Related