Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Pair Generator: How to stop people coming up multiple times?

I am creating a tiny little python programme that needs to generate random pairs for some group work I am organising. I need to make sure people and pairs don't appear twice.

Here is what I have written so far. I feel close but don't quite know how to fix it.

I am getting two lists of people I need to pair together from two .txt files and they are being randomly generated no problem. But I am getting repeats in the output.

I am currently going down the route of creating lists and checking if they are in that list but is there a simpler way?

import random

def split_file(file_name):
  text = open(file_name)
  line = text.read()
  result = line.split("\n")
  return result

mentors = split_file(file_name="mentors.txt")
mentees = split_file(file_name="mentees.txt")

def randomiser(group):
  random_member = random.choice(group)
  return random_member

pairings = []
mentees_list = []
mentors_list = []

for i in range(20):
  mentee = randomiser(mentees)
  if mentee not in mentees_list:
     mentees_list.append(mentee)
  mentor = randomiser(mentors)
  if mentor not in mentors_list:
    mentees_list.append(mentee)
  pair = mentee + ", " + mentor
  if pair not in pairings:
      pairings.append(pair)
      print(pair)
like image 406
Fin-AI-dev Avatar asked Dec 30 '25 12:12

Fin-AI-dev


1 Answers

Using random.shuffle and zip you can quickly pair two lists randomly:

import random

mentors = ['a', 'b', 'c', 'd', 'e']
mentees = [1, 2, 3, 4, 5]

random.shuffle(mentors)
random.shuffle(mentees)

pairs = [*zip(mentors, mentees)]

output:

[('b', 5), ('c', 1), ('a', 2), ('d', 4), ('e', 3)]
like image 143
Or Y Avatar answered Jan 01 '26 02:01

Or Y



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!