Razzle Dazzle simulatorAirport SimulatorDistributed system simulatorCircuit SimulatorPHP Lottery SimulatorMonty Hall simulator in Python 3.xSimple game outcome simulatorMonty Hall Simulator - PythonGreed Dice Scoring Game expanded - Python KoansC++ Beginner Bunny ExerciseLotto simulator in Python
Rail-to-rail op-amp only reaches 90% of VCC, works sometimes, not everytime
Converting from CMYK to RGB (to work with it), then back to CMYK
That's not my X, its Y is too Z
Does putting salt first make it easier for attacker to bruteforce the hash?
A Salute to Poetry
How was the airlock installed on the Space Shuttle mid deck?
Why did Intel abandon unified CPU cache?
Assigning function to function pointer, const argument correctness?
Remove border lines of SRTM tiles rendered as hillshade
How to befriend someone who doesn't like to talk?
Is there a DSLR/mirorless camera with minimal options like a classic, simple SLR?
Is Lambda Calculus purely syntactic?
C++ logging library
Could a person damage a jet airliner - from the outside - with their bare hands?
Why do radiation hardened IC packages often have long leads?
How can I remove material from this wood beam?
bash vs. zsh: What are the practical differences?
The significance of kelvin as a unit of absolute temperature
How (un)safe is it to ride barefoot?
How can powerful telekinesis avoid violating Newton's 3rd Law?
To what extent do precedents in Westminster systems apply in other countries that use it?
What do Birth, Age, and Death mean in the first noble truth?
Why isn't Bash trap working if output is redirected to stdout?
Use 1 9 6 2 in this order to make 75
Razzle Dazzle simulator
Airport SimulatorDistributed system simulatorCircuit SimulatorPHP Lottery SimulatorMonty Hall simulator in Python 3.xSimple game outcome simulatorMonty Hall Simulator - PythonGreed Dice Scoring Game expanded - Python KoansC++ Beginner Bunny ExerciseLotto simulator in Python
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Inspired by the video from Scam Nation and James Grime from Numberphile, I tried to make a Razzle Dazzle simulator.
Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice instead can also be done. The scores are added to form a score from 8 to 48. This score is translated into points via table/chart. The points are accumulated across turns. When the player reaches 100 points, it wins a prize. Some scores increase the number of prizes when 100 points are reached. A score of 29 doubles the fee per turn, multiplicatively, so scoring 29 10 times increases the fee to 1024x the initial fee.
The trick is that the most common scores (22-34) do not give any points. This means that only 2.7% of the turns by fair dice rolls give out points, needing 369.5 turns to reach 100 points. For the board in the video, only 0.28% give points, resulting in 5000+ turns to get 100 points. The probability to score 29 is about 8%, this leads to massive fees when playing lots of turns.
import random, numpy
import matplotlib.pyplot as plt
# return one int with random value [1,6], with the probability density described in rawMassDist
# every 1000 turns, sample 1000 loaded die throws and put them in a list
randoms = []
idxRandom = 0
def throwLoadedDie():
global idxRandom
global randoms
rawMassDist = [11, 17, 39, 44, 21, 11]
#rawMassDist = [50, 5, 5, 5, 5, 50]
massDist = [float(i)/sum(rawMassDist) for i in rawMassDist]
if (idxRandom % 1000) == 0:
#randoms = numpy.random.choice(range(1, 7), size=1000, p=massDist)
randoms = random.choices(range(1,7), massDist, k=1000)
idxRandom = 0
idxRandom += 1
return randoms[idxRandom-1]
# throw 8 dice, fairDice indicates whether fair dice or loaded dice are used
# returns the sum of the dice values, which equals the score for this turn
def throwDice():
total = 0
for _ in range(0,8):
if fairDice:
total += random.randint(1,6);
else:
total += throwLoadedDie()
return total
# translates the score into points using dictionary toPoints
def getPoints(score):
toPoints = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
if score in toPoints:
return toPoints[score]
return 0
# returns if this score results in an extra price
def isExtraPrize(score):
if (18 <= score <= 21) or (score == 29) or (35 <= score <= 38):
return True
return False
# returns if this score doubles the fee for one turn
def needDoubleFee(score):
return score == 29
# simulate one turn, return the new number of points, prizes and fee for the next turn
def simulateTurn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return [points, prizes, fee, score]
# simulate single game, can result in win or loss in maxTurns turns
# can print result and histogram of scores
def playGame(printResult = True, maxTurns = 1000):
points = 0
prizes = 1
hist = list() # start with empty list, add score after every turn
hist2 = [0]*49 # entries 0-7 is always 0, other entries 8-48 represent the number of times a score has occurred
fee = 1
totalFee = 0
goal = 100
won = False
for turn in range(1, maxTurns+1):
#print('Turn 0, points: 1'.format(turn, points))
totalFee += fee
[points, prizes, fee, score] = simulateTurn(points, prizes, fee)
hist.append(score)
if points >= goal:
won = True
break
# finalize
[hist2, _] = numpy.histogram(hist, bins=49, range=[0,48])
if printResult:
if won:
print('You win 0 prizes in 1 turns, cost: 2'.format(prizes, turn, totalFee))
else:
print('You only got 0 points in 1 turns, cost: 2'.format(points, turn, totalFee))
print(hist2)
if not won:
prizes = 0
return [prizes, turn, totalFee, hist2]
# simulate multiple games, allow many turns per game to practically ensure win
# also disable result printing in each game
def playGames(numGames, plot=False):
hist = [0]*49
totalPrizes = 0
totalTurns = 0
totalFee = 0
withPoints = 0
gamesLost = 0
for i in range(0, numGames):
[prizes, turns, fee, hist2] = playGame(False, 100000)
if prizes == 0:
gamesLost += 1
hist = [x + y for x, y in zip(hist, hist2)]
totalPrizes += prizes
totalFee += fee
totalTurns += turns
for i in range(8, 18):
withPoints += hist[i]
for i in range(39, 49):
withPoints += hist[i]
print('0 games, lost 1'.format(numGames, gamesLost))
print('Avg prizes: '.format(totalPrizes/numGames))
print('Avg turns: '.format(totalTurns/numGames))
print('Avg fee: '.format(totalFee/numGames))
print(hist)
print('Percentage turns with points: :.2f'.format(100.0*withPoints/sum(hist)))
if plot:
# create list of colors to color each bar differently
colors = [item for sublist in [['red']*18, ['blue']*21, ['red']*10] for item in sublist]
plt.bar(range(0, 49), hist, color=colors)
plt.title('Score distribution across multiple games')
plt.xlabel('Score = sum of 8 dice')
plt.ylabel('Number of turns')
plt.text(40, 0.6*max(hist), 'Red barsngive points')
plt.show()
fairDice = False
#playGame()
playGames(100, plot=True)
Concrete questions:
1. Since calling random.choices()
has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables
2. To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?
3. How are my names? Especially hist
, hist2
, isExtraPrize()
and needDoubleFee()
4. My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging
3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome
5. And of course, general code review answers are welcome
python performance simulation
$endgroup$
add a comment |
$begingroup$
Inspired by the video from Scam Nation and James Grime from Numberphile, I tried to make a Razzle Dazzle simulator.
Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice instead can also be done. The scores are added to form a score from 8 to 48. This score is translated into points via table/chart. The points are accumulated across turns. When the player reaches 100 points, it wins a prize. Some scores increase the number of prizes when 100 points are reached. A score of 29 doubles the fee per turn, multiplicatively, so scoring 29 10 times increases the fee to 1024x the initial fee.
The trick is that the most common scores (22-34) do not give any points. This means that only 2.7% of the turns by fair dice rolls give out points, needing 369.5 turns to reach 100 points. For the board in the video, only 0.28% give points, resulting in 5000+ turns to get 100 points. The probability to score 29 is about 8%, this leads to massive fees when playing lots of turns.
import random, numpy
import matplotlib.pyplot as plt
# return one int with random value [1,6], with the probability density described in rawMassDist
# every 1000 turns, sample 1000 loaded die throws and put them in a list
randoms = []
idxRandom = 0
def throwLoadedDie():
global idxRandom
global randoms
rawMassDist = [11, 17, 39, 44, 21, 11]
#rawMassDist = [50, 5, 5, 5, 5, 50]
massDist = [float(i)/sum(rawMassDist) for i in rawMassDist]
if (idxRandom % 1000) == 0:
#randoms = numpy.random.choice(range(1, 7), size=1000, p=massDist)
randoms = random.choices(range(1,7), massDist, k=1000)
idxRandom = 0
idxRandom += 1
return randoms[idxRandom-1]
# throw 8 dice, fairDice indicates whether fair dice or loaded dice are used
# returns the sum of the dice values, which equals the score for this turn
def throwDice():
total = 0
for _ in range(0,8):
if fairDice:
total += random.randint(1,6);
else:
total += throwLoadedDie()
return total
# translates the score into points using dictionary toPoints
def getPoints(score):
toPoints = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
if score in toPoints:
return toPoints[score]
return 0
# returns if this score results in an extra price
def isExtraPrize(score):
if (18 <= score <= 21) or (score == 29) or (35 <= score <= 38):
return True
return False
# returns if this score doubles the fee for one turn
def needDoubleFee(score):
return score == 29
# simulate one turn, return the new number of points, prizes and fee for the next turn
def simulateTurn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return [points, prizes, fee, score]
# simulate single game, can result in win or loss in maxTurns turns
# can print result and histogram of scores
def playGame(printResult = True, maxTurns = 1000):
points = 0
prizes = 1
hist = list() # start with empty list, add score after every turn
hist2 = [0]*49 # entries 0-7 is always 0, other entries 8-48 represent the number of times a score has occurred
fee = 1
totalFee = 0
goal = 100
won = False
for turn in range(1, maxTurns+1):
#print('Turn 0, points: 1'.format(turn, points))
totalFee += fee
[points, prizes, fee, score] = simulateTurn(points, prizes, fee)
hist.append(score)
if points >= goal:
won = True
break
# finalize
[hist2, _] = numpy.histogram(hist, bins=49, range=[0,48])
if printResult:
if won:
print('You win 0 prizes in 1 turns, cost: 2'.format(prizes, turn, totalFee))
else:
print('You only got 0 points in 1 turns, cost: 2'.format(points, turn, totalFee))
print(hist2)
if not won:
prizes = 0
return [prizes, turn, totalFee, hist2]
# simulate multiple games, allow many turns per game to practically ensure win
# also disable result printing in each game
def playGames(numGames, plot=False):
hist = [0]*49
totalPrizes = 0
totalTurns = 0
totalFee = 0
withPoints = 0
gamesLost = 0
for i in range(0, numGames):
[prizes, turns, fee, hist2] = playGame(False, 100000)
if prizes == 0:
gamesLost += 1
hist = [x + y for x, y in zip(hist, hist2)]
totalPrizes += prizes
totalFee += fee
totalTurns += turns
for i in range(8, 18):
withPoints += hist[i]
for i in range(39, 49):
withPoints += hist[i]
print('0 games, lost 1'.format(numGames, gamesLost))
print('Avg prizes: '.format(totalPrizes/numGames))
print('Avg turns: '.format(totalTurns/numGames))
print('Avg fee: '.format(totalFee/numGames))
print(hist)
print('Percentage turns with points: :.2f'.format(100.0*withPoints/sum(hist)))
if plot:
# create list of colors to color each bar differently
colors = [item for sublist in [['red']*18, ['blue']*21, ['red']*10] for item in sublist]
plt.bar(range(0, 49), hist, color=colors)
plt.title('Score distribution across multiple games')
plt.xlabel('Score = sum of 8 dice')
plt.ylabel('Number of turns')
plt.text(40, 0.6*max(hist), 'Red barsngive points')
plt.show()
fairDice = False
#playGame()
playGames(100, plot=True)
Concrete questions:
1. Since calling random.choices()
has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables
2. To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?
3. How are my names? Especially hist
, hist2
, isExtraPrize()
and needDoubleFee()
4. My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging
3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome
5. And of course, general code review answers are welcome
python performance simulation
$endgroup$
add a comment |
$begingroup$
Inspired by the video from Scam Nation and James Grime from Numberphile, I tried to make a Razzle Dazzle simulator.
Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice instead can also be done. The scores are added to form a score from 8 to 48. This score is translated into points via table/chart. The points are accumulated across turns. When the player reaches 100 points, it wins a prize. Some scores increase the number of prizes when 100 points are reached. A score of 29 doubles the fee per turn, multiplicatively, so scoring 29 10 times increases the fee to 1024x the initial fee.
The trick is that the most common scores (22-34) do not give any points. This means that only 2.7% of the turns by fair dice rolls give out points, needing 369.5 turns to reach 100 points. For the board in the video, only 0.28% give points, resulting in 5000+ turns to get 100 points. The probability to score 29 is about 8%, this leads to massive fees when playing lots of turns.
import random, numpy
import matplotlib.pyplot as plt
# return one int with random value [1,6], with the probability density described in rawMassDist
# every 1000 turns, sample 1000 loaded die throws and put them in a list
randoms = []
idxRandom = 0
def throwLoadedDie():
global idxRandom
global randoms
rawMassDist = [11, 17, 39, 44, 21, 11]
#rawMassDist = [50, 5, 5, 5, 5, 50]
massDist = [float(i)/sum(rawMassDist) for i in rawMassDist]
if (idxRandom % 1000) == 0:
#randoms = numpy.random.choice(range(1, 7), size=1000, p=massDist)
randoms = random.choices(range(1,7), massDist, k=1000)
idxRandom = 0
idxRandom += 1
return randoms[idxRandom-1]
# throw 8 dice, fairDice indicates whether fair dice or loaded dice are used
# returns the sum of the dice values, which equals the score for this turn
def throwDice():
total = 0
for _ in range(0,8):
if fairDice:
total += random.randint(1,6);
else:
total += throwLoadedDie()
return total
# translates the score into points using dictionary toPoints
def getPoints(score):
toPoints = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
if score in toPoints:
return toPoints[score]
return 0
# returns if this score results in an extra price
def isExtraPrize(score):
if (18 <= score <= 21) or (score == 29) or (35 <= score <= 38):
return True
return False
# returns if this score doubles the fee for one turn
def needDoubleFee(score):
return score == 29
# simulate one turn, return the new number of points, prizes and fee for the next turn
def simulateTurn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return [points, prizes, fee, score]
# simulate single game, can result in win or loss in maxTurns turns
# can print result and histogram of scores
def playGame(printResult = True, maxTurns = 1000):
points = 0
prizes = 1
hist = list() # start with empty list, add score after every turn
hist2 = [0]*49 # entries 0-7 is always 0, other entries 8-48 represent the number of times a score has occurred
fee = 1
totalFee = 0
goal = 100
won = False
for turn in range(1, maxTurns+1):
#print('Turn 0, points: 1'.format(turn, points))
totalFee += fee
[points, prizes, fee, score] = simulateTurn(points, prizes, fee)
hist.append(score)
if points >= goal:
won = True
break
# finalize
[hist2, _] = numpy.histogram(hist, bins=49, range=[0,48])
if printResult:
if won:
print('You win 0 prizes in 1 turns, cost: 2'.format(prizes, turn, totalFee))
else:
print('You only got 0 points in 1 turns, cost: 2'.format(points, turn, totalFee))
print(hist2)
if not won:
prizes = 0
return [prizes, turn, totalFee, hist2]
# simulate multiple games, allow many turns per game to practically ensure win
# also disable result printing in each game
def playGames(numGames, plot=False):
hist = [0]*49
totalPrizes = 0
totalTurns = 0
totalFee = 0
withPoints = 0
gamesLost = 0
for i in range(0, numGames):
[prizes, turns, fee, hist2] = playGame(False, 100000)
if prizes == 0:
gamesLost += 1
hist = [x + y for x, y in zip(hist, hist2)]
totalPrizes += prizes
totalFee += fee
totalTurns += turns
for i in range(8, 18):
withPoints += hist[i]
for i in range(39, 49):
withPoints += hist[i]
print('0 games, lost 1'.format(numGames, gamesLost))
print('Avg prizes: '.format(totalPrizes/numGames))
print('Avg turns: '.format(totalTurns/numGames))
print('Avg fee: '.format(totalFee/numGames))
print(hist)
print('Percentage turns with points: :.2f'.format(100.0*withPoints/sum(hist)))
if plot:
# create list of colors to color each bar differently
colors = [item for sublist in [['red']*18, ['blue']*21, ['red']*10] for item in sublist]
plt.bar(range(0, 49), hist, color=colors)
plt.title('Score distribution across multiple games')
plt.xlabel('Score = sum of 8 dice')
plt.ylabel('Number of turns')
plt.text(40, 0.6*max(hist), 'Red barsngive points')
plt.show()
fairDice = False
#playGame()
playGames(100, plot=True)
Concrete questions:
1. Since calling random.choices()
has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables
2. To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?
3. How are my names? Especially hist
, hist2
, isExtraPrize()
and needDoubleFee()
4. My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging
3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome
5. And of course, general code review answers are welcome
python performance simulation
$endgroup$
Inspired by the video from Scam Nation and James Grime from Numberphile, I tried to make a Razzle Dazzle simulator.
Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice instead can also be done. The scores are added to form a score from 8 to 48. This score is translated into points via table/chart. The points are accumulated across turns. When the player reaches 100 points, it wins a prize. Some scores increase the number of prizes when 100 points are reached. A score of 29 doubles the fee per turn, multiplicatively, so scoring 29 10 times increases the fee to 1024x the initial fee.
The trick is that the most common scores (22-34) do not give any points. This means that only 2.7% of the turns by fair dice rolls give out points, needing 369.5 turns to reach 100 points. For the board in the video, only 0.28% give points, resulting in 5000+ turns to get 100 points. The probability to score 29 is about 8%, this leads to massive fees when playing lots of turns.
import random, numpy
import matplotlib.pyplot as plt
# return one int with random value [1,6], with the probability density described in rawMassDist
# every 1000 turns, sample 1000 loaded die throws and put them in a list
randoms = []
idxRandom = 0
def throwLoadedDie():
global idxRandom
global randoms
rawMassDist = [11, 17, 39, 44, 21, 11]
#rawMassDist = [50, 5, 5, 5, 5, 50]
massDist = [float(i)/sum(rawMassDist) for i in rawMassDist]
if (idxRandom % 1000) == 0:
#randoms = numpy.random.choice(range(1, 7), size=1000, p=massDist)
randoms = random.choices(range(1,7), massDist, k=1000)
idxRandom = 0
idxRandom += 1
return randoms[idxRandom-1]
# throw 8 dice, fairDice indicates whether fair dice or loaded dice are used
# returns the sum of the dice values, which equals the score for this turn
def throwDice():
total = 0
for _ in range(0,8):
if fairDice:
total += random.randint(1,6);
else:
total += throwLoadedDie()
return total
# translates the score into points using dictionary toPoints
def getPoints(score):
toPoints = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
if score in toPoints:
return toPoints[score]
return 0
# returns if this score results in an extra price
def isExtraPrize(score):
if (18 <= score <= 21) or (score == 29) or (35 <= score <= 38):
return True
return False
# returns if this score doubles the fee for one turn
def needDoubleFee(score):
return score == 29
# simulate one turn, return the new number of points, prizes and fee for the next turn
def simulateTurn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return [points, prizes, fee, score]
# simulate single game, can result in win or loss in maxTurns turns
# can print result and histogram of scores
def playGame(printResult = True, maxTurns = 1000):
points = 0
prizes = 1
hist = list() # start with empty list, add score after every turn
hist2 = [0]*49 # entries 0-7 is always 0, other entries 8-48 represent the number of times a score has occurred
fee = 1
totalFee = 0
goal = 100
won = False
for turn in range(1, maxTurns+1):
#print('Turn 0, points: 1'.format(turn, points))
totalFee += fee
[points, prizes, fee, score] = simulateTurn(points, prizes, fee)
hist.append(score)
if points >= goal:
won = True
break
# finalize
[hist2, _] = numpy.histogram(hist, bins=49, range=[0,48])
if printResult:
if won:
print('You win 0 prizes in 1 turns, cost: 2'.format(prizes, turn, totalFee))
else:
print('You only got 0 points in 1 turns, cost: 2'.format(points, turn, totalFee))
print(hist2)
if not won:
prizes = 0
return [prizes, turn, totalFee, hist2]
# simulate multiple games, allow many turns per game to practically ensure win
# also disable result printing in each game
def playGames(numGames, plot=False):
hist = [0]*49
totalPrizes = 0
totalTurns = 0
totalFee = 0
withPoints = 0
gamesLost = 0
for i in range(0, numGames):
[prizes, turns, fee, hist2] = playGame(False, 100000)
if prizes == 0:
gamesLost += 1
hist = [x + y for x, y in zip(hist, hist2)]
totalPrizes += prizes
totalFee += fee
totalTurns += turns
for i in range(8, 18):
withPoints += hist[i]
for i in range(39, 49):
withPoints += hist[i]
print('0 games, lost 1'.format(numGames, gamesLost))
print('Avg prizes: '.format(totalPrizes/numGames))
print('Avg turns: '.format(totalTurns/numGames))
print('Avg fee: '.format(totalFee/numGames))
print(hist)
print('Percentage turns with points: :.2f'.format(100.0*withPoints/sum(hist)))
if plot:
# create list of colors to color each bar differently
colors = [item for sublist in [['red']*18, ['blue']*21, ['red']*10] for item in sublist]
plt.bar(range(0, 49), hist, color=colors)
plt.title('Score distribution across multiple games')
plt.xlabel('Score = sum of 8 dice')
plt.ylabel('Number of turns')
plt.text(40, 0.6*max(hist), 'Red barsngive points')
plt.show()
fairDice = False
#playGame()
playGames(100, plot=True)
Concrete questions:
1. Since calling random.choices()
has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables
2. To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?
3. How are my names? Especially hist
, hist2
, isExtraPrize()
and needDoubleFee()
4. My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging
3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome
5. And of course, general code review answers are welcome
python performance simulation
python performance simulation
asked 9 hours ago
user2966394user2966394
895
895
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.
I think throw_dice
can be improved a bit. You're checking for the value of fair_dice
once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.
There's different ways of approaching this depending on how close to PEP you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:
def throw_loaded_die():
return 1 # For brevity
# Break this off into its own function
def throw_fair_die():
return random.randint(1, 6)
def throw_dice():
# Figure out what we need first
roll_f = throw_fair_die if fair_dice else throw_loaded_die
total = 0
for _ in range(8):
total += roll_f() # Then use it here
return total
That cuts down on duplication which is nice. I also got rid of the 0
argument in the call to range
as that's implicit if it isn't specified.
I think the separate def throw_fair_die
is unfortunate though. For such a simple function, I find it to be noisy, and looking around, I'm not the only one to feel this way. Personally, I'd prefer to just write:
def throw_dice():
# Notice the lambda
roll_f = (lambda: random.randint(1, 6)) if fair_dice else throwLoadedDie
total = 0
for _ in range(8): # Specifying the start is unnecessary when it's 0
total += roll_f()
return total
This is arguably a "named lambda" though, which is in violation of the recommendations of PEP:
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
¯_(ツ)_/¯
I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:
def throw_dice():
roll_f = throw_fair_die if fair_dice else throw_loaded_die
return sum(roll_f() for _ in range(8))
is_extra_prize
has a redundant return. It can be simplified to:
def is_extra_prize(score):
return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)
I'll point out though that right below it you have need_double_fee
. Either it's justified to have score == 29
broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:
def need_double_fee(score):
return score == 29
def is_extra_prize(score):
return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)
Although it could be argued that the other two parts of the condition in is_extra_prize
are more complicated than score == 29
, and may benefit from having a name attached to them as well. There's also the alternative of naming the 29
magic number directly, which I feel would probably be an even better option:
EXTRA_PRIZE_SCORE = 29
def is_extra_prize(score):
return (18 <= score <= 21) or score == EXTRA_PRIZE_SCORE or (35 <= score <= 38)
You may find naming 18
, 21
, 35
and 38
are beneficial as well; although that will certainly make that function more verbose.
I think get_points
can be improved as well. The score dictionary seems like it's a "member of the entire program", not something that should be local to the function. You can also use get
on the dictionary to avoid the explicit membership lookup:
SCORE_TO_POINTS = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
def get_points(score):
# 0 is the default if the key doesn't exist
return SCORE_TO_POINTS.get(score, 0)
simulate_turn
returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a named tuple as a shortcut.
In that same function, I'd also add some lines to space things out a bit:
def simulate_turn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return (points, prizes, fee, score)
Personal style, but I like open space in code.
You could also do away with the mutation of the parameters:
def simulate_turn(points, prizes, fee):
score = throwDice()
return (points + getPoints(score),
prizes + 1 if isExtraPrize(score) else prizes,
fee * 2 if needDoubleFee(score) else fee,
score)
Although now that it's written out, I'm not sure how I feel about it.
I really only dealt with 5.
here. Hopefully someone else can touch on the first four points.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221972%2frazzle-dazzle-simulator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.
I think throw_dice
can be improved a bit. You're checking for the value of fair_dice
once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.
There's different ways of approaching this depending on how close to PEP you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:
def throw_loaded_die():
return 1 # For brevity
# Break this off into its own function
def throw_fair_die():
return random.randint(1, 6)
def throw_dice():
# Figure out what we need first
roll_f = throw_fair_die if fair_dice else throw_loaded_die
total = 0
for _ in range(8):
total += roll_f() # Then use it here
return total
That cuts down on duplication which is nice. I also got rid of the 0
argument in the call to range
as that's implicit if it isn't specified.
I think the separate def throw_fair_die
is unfortunate though. For such a simple function, I find it to be noisy, and looking around, I'm not the only one to feel this way. Personally, I'd prefer to just write:
def throw_dice():
# Notice the lambda
roll_f = (lambda: random.randint(1, 6)) if fair_dice else throwLoadedDie
total = 0
for _ in range(8): # Specifying the start is unnecessary when it's 0
total += roll_f()
return total
This is arguably a "named lambda" though, which is in violation of the recommendations of PEP:
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
¯_(ツ)_/¯
I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:
def throw_dice():
roll_f = throw_fair_die if fair_dice else throw_loaded_die
return sum(roll_f() for _ in range(8))
is_extra_prize
has a redundant return. It can be simplified to:
def is_extra_prize(score):
return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)
I'll point out though that right below it you have need_double_fee
. Either it's justified to have score == 29
broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:
def need_double_fee(score):
return score == 29
def is_extra_prize(score):
return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)
Although it could be argued that the other two parts of the condition in is_extra_prize
are more complicated than score == 29
, and may benefit from having a name attached to them as well. There's also the alternative of naming the 29
magic number directly, which I feel would probably be an even better option:
EXTRA_PRIZE_SCORE = 29
def is_extra_prize(score):
return (18 <= score <= 21) or score == EXTRA_PRIZE_SCORE or (35 <= score <= 38)
You may find naming 18
, 21
, 35
and 38
are beneficial as well; although that will certainly make that function more verbose.
I think get_points
can be improved as well. The score dictionary seems like it's a "member of the entire program", not something that should be local to the function. You can also use get
on the dictionary to avoid the explicit membership lookup:
SCORE_TO_POINTS = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
def get_points(score):
# 0 is the default if the key doesn't exist
return SCORE_TO_POINTS.get(score, 0)
simulate_turn
returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a named tuple as a shortcut.
In that same function, I'd also add some lines to space things out a bit:
def simulate_turn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return (points, prizes, fee, score)
Personal style, but I like open space in code.
You could also do away with the mutation of the parameters:
def simulate_turn(points, prizes, fee):
score = throwDice()
return (points + getPoints(score),
prizes + 1 if isExtraPrize(score) else prizes,
fee * 2 if needDoubleFee(score) else fee,
score)
Although now that it's written out, I'm not sure how I feel about it.
I really only dealt with 5.
here. Hopefully someone else can touch on the first four points.
$endgroup$
add a comment |
$begingroup$
First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.
I think throw_dice
can be improved a bit. You're checking for the value of fair_dice
once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.
There's different ways of approaching this depending on how close to PEP you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:
def throw_loaded_die():
return 1 # For brevity
# Break this off into its own function
def throw_fair_die():
return random.randint(1, 6)
def throw_dice():
# Figure out what we need first
roll_f = throw_fair_die if fair_dice else throw_loaded_die
total = 0
for _ in range(8):
total += roll_f() # Then use it here
return total
That cuts down on duplication which is nice. I also got rid of the 0
argument in the call to range
as that's implicit if it isn't specified.
I think the separate def throw_fair_die
is unfortunate though. For such a simple function, I find it to be noisy, and looking around, I'm not the only one to feel this way. Personally, I'd prefer to just write:
def throw_dice():
# Notice the lambda
roll_f = (lambda: random.randint(1, 6)) if fair_dice else throwLoadedDie
total = 0
for _ in range(8): # Specifying the start is unnecessary when it's 0
total += roll_f()
return total
This is arguably a "named lambda" though, which is in violation of the recommendations of PEP:
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
¯_(ツ)_/¯
I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:
def throw_dice():
roll_f = throw_fair_die if fair_dice else throw_loaded_die
return sum(roll_f() for _ in range(8))
is_extra_prize
has a redundant return. It can be simplified to:
def is_extra_prize(score):
return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)
I'll point out though that right below it you have need_double_fee
. Either it's justified to have score == 29
broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:
def need_double_fee(score):
return score == 29
def is_extra_prize(score):
return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)
Although it could be argued that the other two parts of the condition in is_extra_prize
are more complicated than score == 29
, and may benefit from having a name attached to them as well. There's also the alternative of naming the 29
magic number directly, which I feel would probably be an even better option:
EXTRA_PRIZE_SCORE = 29
def is_extra_prize(score):
return (18 <= score <= 21) or score == EXTRA_PRIZE_SCORE or (35 <= score <= 38)
You may find naming 18
, 21
, 35
and 38
are beneficial as well; although that will certainly make that function more verbose.
I think get_points
can be improved as well. The score dictionary seems like it's a "member of the entire program", not something that should be local to the function. You can also use get
on the dictionary to avoid the explicit membership lookup:
SCORE_TO_POINTS = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
def get_points(score):
# 0 is the default if the key doesn't exist
return SCORE_TO_POINTS.get(score, 0)
simulate_turn
returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a named tuple as a shortcut.
In that same function, I'd also add some lines to space things out a bit:
def simulate_turn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return (points, prizes, fee, score)
Personal style, but I like open space in code.
You could also do away with the mutation of the parameters:
def simulate_turn(points, prizes, fee):
score = throwDice()
return (points + getPoints(score),
prizes + 1 if isExtraPrize(score) else prizes,
fee * 2 if needDoubleFee(score) else fee,
score)
Although now that it's written out, I'm not sure how I feel about it.
I really only dealt with 5.
here. Hopefully someone else can touch on the first four points.
$endgroup$
add a comment |
$begingroup$
First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.
I think throw_dice
can be improved a bit. You're checking for the value of fair_dice
once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.
There's different ways of approaching this depending on how close to PEP you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:
def throw_loaded_die():
return 1 # For brevity
# Break this off into its own function
def throw_fair_die():
return random.randint(1, 6)
def throw_dice():
# Figure out what we need first
roll_f = throw_fair_die if fair_dice else throw_loaded_die
total = 0
for _ in range(8):
total += roll_f() # Then use it here
return total
That cuts down on duplication which is nice. I also got rid of the 0
argument in the call to range
as that's implicit if it isn't specified.
I think the separate def throw_fair_die
is unfortunate though. For such a simple function, I find it to be noisy, and looking around, I'm not the only one to feel this way. Personally, I'd prefer to just write:
def throw_dice():
# Notice the lambda
roll_f = (lambda: random.randint(1, 6)) if fair_dice else throwLoadedDie
total = 0
for _ in range(8): # Specifying the start is unnecessary when it's 0
total += roll_f()
return total
This is arguably a "named lambda" though, which is in violation of the recommendations of PEP:
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
¯_(ツ)_/¯
I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:
def throw_dice():
roll_f = throw_fair_die if fair_dice else throw_loaded_die
return sum(roll_f() for _ in range(8))
is_extra_prize
has a redundant return. It can be simplified to:
def is_extra_prize(score):
return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)
I'll point out though that right below it you have need_double_fee
. Either it's justified to have score == 29
broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:
def need_double_fee(score):
return score == 29
def is_extra_prize(score):
return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)
Although it could be argued that the other two parts of the condition in is_extra_prize
are more complicated than score == 29
, and may benefit from having a name attached to them as well. There's also the alternative of naming the 29
magic number directly, which I feel would probably be an even better option:
EXTRA_PRIZE_SCORE = 29
def is_extra_prize(score):
return (18 <= score <= 21) or score == EXTRA_PRIZE_SCORE or (35 <= score <= 38)
You may find naming 18
, 21
, 35
and 38
are beneficial as well; although that will certainly make that function more verbose.
I think get_points
can be improved as well. The score dictionary seems like it's a "member of the entire program", not something that should be local to the function. You can also use get
on the dictionary to avoid the explicit membership lookup:
SCORE_TO_POINTS = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
def get_points(score):
# 0 is the default if the key doesn't exist
return SCORE_TO_POINTS.get(score, 0)
simulate_turn
returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a named tuple as a shortcut.
In that same function, I'd also add some lines to space things out a bit:
def simulate_turn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return (points, prizes, fee, score)
Personal style, but I like open space in code.
You could also do away with the mutation of the parameters:
def simulate_turn(points, prizes, fee):
score = throwDice()
return (points + getPoints(score),
prizes + 1 if isExtraPrize(score) else prizes,
fee * 2 if needDoubleFee(score) else fee,
score)
Although now that it's written out, I'm not sure how I feel about it.
I really only dealt with 5.
here. Hopefully someone else can touch on the first four points.
$endgroup$
First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.
I think throw_dice
can be improved a bit. You're checking for the value of fair_dice
once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.
There's different ways of approaching this depending on how close to PEP you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:
def throw_loaded_die():
return 1 # For brevity
# Break this off into its own function
def throw_fair_die():
return random.randint(1, 6)
def throw_dice():
# Figure out what we need first
roll_f = throw_fair_die if fair_dice else throw_loaded_die
total = 0
for _ in range(8):
total += roll_f() # Then use it here
return total
That cuts down on duplication which is nice. I also got rid of the 0
argument in the call to range
as that's implicit if it isn't specified.
I think the separate def throw_fair_die
is unfortunate though. For such a simple function, I find it to be noisy, and looking around, I'm not the only one to feel this way. Personally, I'd prefer to just write:
def throw_dice():
# Notice the lambda
roll_f = (lambda: random.randint(1, 6)) if fair_dice else throwLoadedDie
total = 0
for _ in range(8): # Specifying the start is unnecessary when it's 0
total += roll_f()
return total
This is arguably a "named lambda" though, which is in violation of the recommendations of PEP:
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
¯_(ツ)_/¯
I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:
def throw_dice():
roll_f = throw_fair_die if fair_dice else throw_loaded_die
return sum(roll_f() for _ in range(8))
is_extra_prize
has a redundant return. It can be simplified to:
def is_extra_prize(score):
return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)
I'll point out though that right below it you have need_double_fee
. Either it's justified to have score == 29
broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:
def need_double_fee(score):
return score == 29
def is_extra_prize(score):
return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)
Although it could be argued that the other two parts of the condition in is_extra_prize
are more complicated than score == 29
, and may benefit from having a name attached to them as well. There's also the alternative of naming the 29
magic number directly, which I feel would probably be an even better option:
EXTRA_PRIZE_SCORE = 29
def is_extra_prize(score):
return (18 <= score <= 21) or score == EXTRA_PRIZE_SCORE or (35 <= score <= 38)
You may find naming 18
, 21
, 35
and 38
are beneficial as well; although that will certainly make that function more verbose.
I think get_points
can be improved as well. The score dictionary seems like it's a "member of the entire program", not something that should be local to the function. You can also use get
on the dictionary to avoid the explicit membership lookup:
SCORE_TO_POINTS = 8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100
def get_points(score):
# 0 is the default if the key doesn't exist
return SCORE_TO_POINTS.get(score, 0)
simulate_turn
returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a named tuple as a shortcut.
In that same function, I'd also add some lines to space things out a bit:
def simulate_turn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return (points, prizes, fee, score)
Personal style, but I like open space in code.
You could also do away with the mutation of the parameters:
def simulate_turn(points, prizes, fee):
score = throwDice()
return (points + getPoints(score),
prizes + 1 if isExtraPrize(score) else prizes,
fee * 2 if needDoubleFee(score) else fee,
score)
Although now that it's written out, I'm not sure how I feel about it.
I really only dealt with 5.
here. Hopefully someone else can touch on the first four points.
answered 2 hours ago
CarcigenicateCarcigenicate
4,91111737
4,91111737
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221972%2frazzle-dazzle-simulator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown