list - Python data structure for dice roll emulator -
so made dice rolling simulator in python, , while want told implement lists or dictionary , "better" code. have tried adding both code , lost. if of help/show me awesome. here's code, much.
from random import randint print "" die_amount = raw_input(">how many dice roll?: " ) die_amount = int(die_amount) print "" print "\t %s die being rolled:" % die_amount def dieroll(die_amount): 1 = 0 2 = 0 3 = 0 4 = 0 5 = 0 6 = 0 in range(1, die_amount+1): roll = randint(1,6) print "\t rolled: %s" % roll if roll == 1: 1 +=1 elif roll == 2: 2 +=1 elif roll ==3: 3 +=1 elif roll == 4: 4 +=1 elif roll == 5: five+=1 elif roll == 6: 6 +=1 print """ one's rolled: %s two's rolled: %s three's rolled: %s four's rolled: %s five's rolled: %s six's rolled: %s """ % (one, two, three, four, five, 6 ) return [one, two, three, four, five, six] dieroll(die_amount)
a counter
data structure trying do.
from collections import counter c = counter() in range(die_amount): roll = randint(1,6) c[roll] += 1
or, easier:
c = counter(randint(1,6) in range(die_amount))
c[1]
contains number of times 1
rolled etc.
to print out roll counts, can use
for number, count in c.iteritems(): print "{}'s rolled: {}".format(number, count)
a counter
python dictionary default value of zero. makes particularly suitable counting how many objects occur in list, instance.
there several reasons why approach works better keeping separate variable each count.
if wanted have hundred-sided dice, have define 100 separate variables. that's more error prone.
it's, in principle, faster. having 6 different variables necessitates looping through them series of if-statements. imagine roll six. have evaluate 5 different if-statements until
if roll == 6
. contrast, counter uses hash table,c[roll]
takes same amount of time, regardless of how many rolls make.
this begs question: how can know when should using collection opposed set of variables? rule of thumb if set of objects different instances of same thing, , intend use each object in same manner, belong in collection. in case, roll of 1 or roll of 4 identical far program flow concerned. treat them identically. should therefore kept in collection.
Comments
Post a Comment