Splitting N persons into teams of 2

Viewed 235

I have made the following piece of code to split N persons into random teams of 2, but in many cases, I get the error: pop index out of range.

Could someone help me?

from random import seed
from random import randrange
from datetime import datetime
seed(datetime.now())

N = int(input("How many students do you have?:"))

pupils = set()

for number in range(N):
    pupils.add(str(input('pupil name:')))
print(pupils)


teams = set()
lista = list(pupils)
for i in range(N//2):#// akerea dieresi
    pos1 = randrange(0, len(lista))
    pos2 = randrange(0, len(lista))
    pupil1 = lista.pop(pos1)
    pupil2 = lista.pop(pos2)
    team = (pupil1,pupil2)
    teams.add(team)

i = 0
for team in teams:
    i+=1
    print(team + str(i))
2 Answers

edit: this error means to say that you are trying to pop() from an index that is not on the list. maybe try to check if the list is already empty each time you try to take something out. I`ll use if lista to verify it is not empty.


teams = set()
lista = list(pupils)
for i in range(N//2):  #notice yo only have to do that N//2 times!
    if lista:                       #check if lista is empty
        pos1 = randrange(0, len(lista))
        pupil1 = lista.pop(pos1)
    if lista:
        pos2 = randrange(0, len(lista))
        pupil2 = lista.pop(pos2)

    team = (pupil1,pupil2)
    teams.add(team)

i = 0
for team in teams:
    i+=1
    print(team + str(i))

Your immediate problem is you are shortening a list, but acting like removed indexes should still exist. Your bigger problem is that you are trying to invent your own random.shuffle(). Your code could be simplified greatly by using the builtin random.shuffle().

import random

#represents the results of your name input system
names = 'Tom Jerry Abbot Costello Regis Kelly Harry Sally Thelma Louise Solomon'.split()

#shuffle all the names
random.shuffle(names)

teams = []

#keep going as long as there are pairs
while len(names) > 1:
    teams.append({names.pop(), names.pop()})

#odd man out
if names:
    print(f"{names.pop()} can't play")

#results
print(*teams, sep='\n')
Related