0

I use Python 2.6.

My code can be edited and run here: http://www.codeskulptor.org/#user12_OQL53Z5Es8yDHRB.py

# set the arguments
teams = 4
rounds = 2 * (teams - 1)

# show the arguments
print teams, "teams"
print rounds, "rounds"

# season is a list of lists
# each sub list is a round
season = rounds*["round"]

# store the first round in season[0]
round = range(1, teams + 1)
season[0] = round[:]

# store the other rounds in season
for j in range(1, rounds):
    round2 = round[:]
    round2[1] = round[teams - 1]
    for i in range(2, teams):
        round2[i] = round[i - 1]
    season[j] = round2[:] 
    round = round2

# print the season    
print season

If there are 4 teams and everyone plays every team twice I want this end result: [1, 2, 3, 4], [1, 4, 2, 3], [1, 3, 4, 2], [1, 2, 3, 4], [1, 4, 2, 3], [1, 3, 4, 2]]. Team 1 stays put and the other teams rotate. Every team moves one position to the right, except team 1 and the last team in the list which moves to the position next to team 1.

I believe the above code works. I am a newbie in Python, so I am looking for better or more elegant code.

Thank you!

Jan Nordgreen
  • 55
  • 1
  • 10

2 Answers2

1

A more readable version:

[...]

first_round = range(1, teams + 1)
season = [first_round]

def rotate(round):
    return [round[0], round[-1]] + round[1:-1]

for i in range(0, rounds - 1):
    previous_round = season[i]
    season.append(rotate(previous_round))

print season
Martin Maillard
  • 2,751
  • 19
  • 24
  • How is it more readable? – Aleph May 09 '13 at 10:00
  • Because it describes what a rotation is and doesn't have nested loops, thus making it clear that a season is a collection of rounds, each one being the rotation of the previous one. I'm not arguing that it is perfect, but it is definitely easier to understand. – Martin Maillard May 09 '13 at 10:13
  • Well, sure, but doesn't using `itertools.permuations` offer more abstraction? The author of the question probably just wants to rotate, not bothering with implementing it himself. Note: this is definitely not bad, but better? I don't know. – Aleph May 09 '13 at 10:19
  • Oh using `itertools.permutations` is probably better yes. – Martin Maillard May 09 '13 at 10:51
1

You can use itertools.permutations to create all permutations, and then select the first set that start with 1:

from itertools import permutations
from math import factorial

season = list(permutations(range(1, teams+1)))[:factorial(teams)/teams]

Or without generating all permutations, get the permutations for the 2 to 4 and then append to 1:

season = [[1] + list(i) for i in permutations(range(2, teams+1))]
Matti John
  • 19,329
  • 7
  • 41
  • 39