roll two fair die in python using int and not a string. here is the code i have and the feedback from my teacher -
from random import randrange def roll(): return randrange(1,7) def rolldice(n): onecount = 0 twocount = 0 threecount = 0 fourcount = 0 fivecount = 0 sixcount = 0 in range (n): dice = roll() if dice == 1: onecount = onecount +1 if dice == 2: twocount = twocount +1 if dice == 3: threecount = threecount +1 if dice == 4: fourcount = fourcount +1 if dice == 5: fivecount = fivecount +1 if dice == 6: sixcount = sixcount +1 return (dice, onecount, twocount, threecount, fourcount, fivecount, sixcount) def rolltwodice(): total = 0 turn in range(2): total += roll() return total def rolltwodicecount(n): twos = 0 turn in range(n): if roll() == 2: twos +=1
message teacher:
>>> rolldice(6000) (4, 996, 1022, 976, 991, 1018, 997
that looks works, once figured out first 1 for.
>>> rolltwodice() 10 >>> rolltwodice() 4 >>> rolltwodice() 6 >>> rolltwodice() 7 >>> >>> rolltwodice() 8 >>> rolltwodice() 8 >>> rolltwodice() 3 >>> rolltwodice() 8 >>> rolltwodice() 6 >>> rolltwodice() 6 >>> rolltwodice() 8 >>> rolltwodice() 6 >>> rolltwodice() 9 >>> rolltwodice() 6 >>> rolltwodice() 6 >>> rolltwodice() 9 >>> rolltwodice() 7 >>> rolltwodice() 9 >>> rolltwodice() 6 >>> rolltwodice() 5 >>> rolltwodice() 7
hmm. no 2, 11, or 12. not problem, though.
>>> rolltwodicecount(36000) traceback (most recent call last): file "<pyshell#28>", line 1, in <module> rolltwodicecount(36000) file "c:/users/jneitzke/downloads/alec25.py", line 41, in rolltwodicecount sevens +=1 unboundlocalerror: local variable 'sevens' referenced before assignment
okay, drove on cliff.
def rolltwodicecount(n): twos = 0 turn in range(n): if roll() == 2: twos +=1 sevens +=1 print ("in", n, "rolls of 2 dice, there were",twos,"twos and",\ sevens,"sevens")
yup. no initialization of seven
.
it's kind of overkill, can complete profile did rolldice
, first one. since have gone direction, that. doesn't scale well, it's okay 2 dice. more, forget it.
the more traditional way using dictionary, word count. scales.
count = {} newvalue = ????? if newvalue in count: count[newvalue] += 1 else: count[newvalue] = 1
you need declare variable sevens
before can read it. operator +=
reads current value of variable on left , appends value finds on right.
def rolltwodicecount(n): twos = 0 sevens = 0 turn in range(n): if roll() == 2: twos +=1 sevens +=1 print ("in", n, "rolls of 2 dice, there were",twos,"twos and",\ sevens,"sevens")
Comments
Post a Comment