3

I am working on a program that generates a single elimination tournament. so far my code looks like this ( i have just started)

amount = int(raw_input("How many teams are playing in this tournament? ")) teams = [] i = 0 while i<amount: teams.append(raw_input("please enter team name: ")) i= i+1 

now i am stuck. I want to randomly pick 2 numbers that will select the teams facing eachother. the numbers cannot repeat at all, and have to range from 1 to "amount". What is the most efficient way to do this?

3 Answers 3

11

Take a look at the random module.

>>> import random >>> teams = ['One team', 'Another team', 'A third team'] >>> team1, team2 = random.sample(teams, 2) >>> print team1 'Another team' >>> print team2 'One team' 
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I checked the documentation, and random.sample() will return two unique values from the list. So as long as each team name is in the list once, this is guaranteed to pick two different team names at random. I don't think there can be any better solution than this!
2
team1 = random.choice(teams) teams.remove(team1) team2 = random.choice(teams) 

I think that should work.

2 Comments

Yes. In Python you can just ask for what you really want: one of the teams chosen randomly. No need to get a random number and use that to get the team, just get a random team.
It depends what you need: This is a way to select 2 teams from a list of size greater than 2. If you're going to have a team left over, you're going to have to make a special case for them (give them a bye or something) regardless of what method you use to pair the teams.
0

I'm not entirely sure what you are asking however to chose random number you can use for example

random.randint(1,10) 

this will give you a random number between 1 to 10

Note: you need to import the random module

import random 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.