Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python program for round robin tournament

Tags:

python

I'm writing a program that allows the user to enter and even number of players and then it will generate a round robin tournament schedule. n/2 * n-1 number of games so that each player plays every other player.

Right now I'm having a hard time generating the list of the number of players the user enters. I'm getting this error:

TypeError: 'int' object not iterable.

I get this error a lot in my programs, so I guess I'm not quite understanding this part of Python, so if someone could explain that as well, I'd appreciate it.

def rounds(players, player_list):
    """determines how many rounds and who plays who in each round"""
    num_games = int((players/2) * (players-1))
    num_rounds = int(players/2)
    player_list = list(players)
    return player_list
like image 230
tinydancer9454 Avatar asked May 23 '26 17:05

tinydancer9454


2 Answers

If you just want to get a list of numbers, you probably want the range() function.

For an actual round-robin tournament, you should look at itertools.combinations.

>>> n = 4
>>> players = range(1,n+1)
>>> players
[1, 2, 3, 4]
>>> list(itertools.combinations(players, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
like image 178
Amber Avatar answered May 26 '26 07:05

Amber


player_list= list(players)

Is what raises the TypeError. This is happening because the list() function only knows how to operate on objects that can be iterated over, and int is not such an object.

From the comments, it seems like you just wanted to create a list with the player numbers (or names, or indices) in it. You can do it like this:

# this will create the list [1,2,3,...players]:
player_list = range(1, players+1) 
# or, the list [0,1,...players-1]: 
player_list = range(players) #  this is equivalent to range(0,players)
like image 36
Nisan.H Avatar answered May 26 '26 05:05

Nisan.H



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!