简体   繁体   中英

python program for round robin tournament

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

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)]
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM