Rolling dice with Python / Würfeln mit Python II

Based on http://uweziegenhagen.de/?p=2741 I created another example, this time the algorithm returns a list of the rolled values.

# for the random selection
from random import choice
# to create the sorted dictionary
import collections
 
def throwDiceList(*args):
	if not args: 
		L = []	
	else:
		L = args[0]
	x = choice(range(1,7))
	L.append(x)
	if x == 6:
		return throwDiceList(L)	
	else:
		return L
 
# little test function
def TestDiceList(n):
	# create a dictionary
	d = {}
	for x in range(0, n):
		wurf = sum(throwDiceList())	
 		# if key is found, just increase its frequency by 1 
		if wurf in d:
			d.update({wurf:d[wurf]+1})
		else:
			# else create new key with initiL frequency 1 
			d.update({wurf:1})
	od = collections.OrderedDict(sorted(d.items()))
	for k, v in od.iteritems(): 
		print k, v
 
TestDiceList(60000)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website