I have a little experience with Python and am trying to become more familiar with it. As an exercise, I've tried coding a program where the ordering of a list of players is determined by the roll of a die. A higher number would place the player ahead of others with lower numbers. Ties would be broken by the tied players rolling again.
Here is an example:
player 1, player 2, player 3 rolls 6, rolls 6, rolls 1 / \ / \ player 1, player 2 player 3 rolls 5, rolls 4 / \ / \ player 1 player 2
Final order: player 1, player 2, player 3
I'm interested in how I could have done this better. In particular, I'm not familiar with much of the Python style guide so making it more pythonic would be nice. Also, I'm not that familiar with unit testing. I've used unittest instead of nose since I was using an online IDE that supports it.
from random import randint from itertools import groupby import unittest def rank_players(playerList, die): tree = [playerList] nextGeneration =  keepPlaying = True while keepPlaying: keepPlaying = False for node in tree: if len(node) == 1: nextGeneration.append(node) else: keepPlaying = True rolls = [die.roll() for i in range(len(node))] turn = sorted(zip(rolls,node), reverse=True) print 'players roll:', turn for key, group in groupby(turn, lambda x: x): nextGeneration.append(list(i for i in group)) tree = nextGeneration nextGeneration =  return [item for sublist in tree for item in sublist] class Die: def __init__(self,rolls=): self.i = -1 self.rolls = rolls def roll(self): self.i = self.i + 1 return self.rolls[self.i] class RankingTest(unittest.TestCase): def testEmpty(self): die = Die() players =  self.assertEquals(rank_players(players,die),) def testOnePlayer(self): die = Die() player = ['player 1'] self.assertEquals(rank_players(player,die),['player 1']) def testTwoPlayer(self): die = Die([6, 1]) players = ['player 1', 'player 2'] self.assertEquals(rank_players(players,die),['player 1', 'player 2']) def testThreePlayer(self): die = Die([6, 6, 1, 4, 5]) players = ['player x', 'player y', 'player z'] self.assertEquals(rank_players(players,die),['player x', 'player y','player z']) def testRunAll(self): self.testEmpty() self.testOnePlayer() self.testTwoPlayer() self.testThreePlayer() if __name__ == '__main__': unittest.main()