Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random pairs without repeats in Python (numpy or itertools)

I have a list of people and want to generate a number of random pairs or triplets so that every person in the list belongs to exactly one pair or triplet (no more, no less).

Example:

>>> people = ["John", "Paul", "George", "Ringo", "David", "Roger", "Richard", "Nick", "Syd"]

>>> generate_random_pairs(people)

[
    ("John", "George"),
    ("Paul", "David"),
    ("Roger", "Nick"),
    ("Ringo", "Richard", "Syd")
]

I've tried different ideas using numpy.random.choice, numpy.random.sample or itertools.permutations but none of them seem to work.

like image 615
Jivan Avatar asked Nov 05 '25 08:11

Jivan


1 Answers

Use the grouper() recipe from itertools:

from itertools import zip_longest
from random import shuffle

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks of size n."
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

people = ["John", "Paul", "George", "Ringo", "David", "Roger", "Richard", "Nick", "Syd"]

shuffle(people)

list(grouper(people, 3, ''))

Example output:

[('Ringo', 'George', 'Syd'),
 ('Richard', 'David', 'John'),
 ('Paul', 'Roger', 'Nick')]
like image 200
RootTwo Avatar answered Nov 07 '25 00:11

RootTwo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!