3

I have a list of all premier league teams:

teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ] 

I need to compute all possible team1-vs-team2 pairings.

At present I have the following code:

oppo = 0 for team in teamlist: print team + "-vs-" + teamlist[oppo] oppo+=1 print team + "-vs-" + teamlist[oppo] oppo+=1 

which will output:

arsenal-vs-arsenal arsenal-vs-aston-villa 

However I need this to go through each team, display all of their possible home game fixtures, then move onto the next team in teamlist, output all of their possible home games fixtures and repeat until all teams are done.

0

3 Answers 3

8

An alternative to the nested for loops is to compute all permutations of length 2 from the items of your list.

>>> from itertools import permutations >>> for team1, team2 in permutations(teamlist, 2): ... print '{0} -vs- {1}'.format(team1, team2) ... arsenal -vs- aston-villa arsenal -vs- bournemouth arsenal -vs- chelsea # and so on ... 
Sign up to request clarification or add additional context in comments.

Comments

3

This can be archieved by looping through the teamlist twice and by checking whether the opponent is "before" the original team. The code does also not depend on external libraries.

teamlist = ["arsenal", "aston-villa", "bournemouth", "chelsea", "crystal-palace", "everton","leicester-city", "liverpool", "manchester-city", "manchester-united", "newcastle-united", "norwich-city", "southampton","stoke-city", "swansea-city", "tottenham-hotspur", "watford", "west-bromich-albion","west-ham-united" ] for team in teamlist: for opponent in teamlist: if team < opponent: print(team + "-vs-" + opponent) 

2 Comments

You'll get duplicate reversed "-vs-" with this solution.
I guess that works... :) I would've done a loop from 0..len then i+1..len
1

Doing this recursively in a function should work.

# after defining teamlist def printVS(start): for x in range(1,len(teamlist)-start): print teamlist[start],"vs",teamlist[start+x] if start < len(teamlist): printVS(start+1) printVS(0) 

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.