Python Forum

Full Version: python how to
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A dictionary with 6 elements: keys are integers 1 to 6, values are corresponding number of 
occurrence Description: 
You roll the dice 10,000 times. Each time you get one of six sides with a probability of 1/6. You need to generate the total number of occurrence for each side, store them in a dictionary as a returned value.
You'll want the random and collections modules.
results = collections.defaultdict(int)
Read the docs about defaultdict and test it.

You can do thinks like:

results['key_which_does_not_exist'] = 1 #or for counting
results['key_which_does_not_exist'] += 1 # if the key does not exist, it's 0
Use this to simulate a result of rolling:

import random
r = int(random.random()*6)
(Oct-08-2018, 11:10 AM)DeaD_EyE Wrote: [ -> ]
results = collections.defaultdict(int)
Read the docs about defaultdict and test it.

You can do thinks like:

results['key_which_does_not_exist'] = 1 #or for counting
results['key_which_does_not_exist'] += 1 # if the key does not exist, it's 0

I think that collections.Counter will be a better choice. One of the advantages of Counter is that you may apply arithmetic operations between objects of that type
(Oct-08-2018, 12:08 PM)zhruser Wrote: [ -> ]Use this to simulate a result of rolling:

import random
r = int(random.random()*6)

Please, use python tags when post code.
Also, you may find interesting to read this
https://docs.python.org/3/library/random...r-integers

Quote:Changed in version 3.2: randrange() is more sophisticated about producing equally distributed values. Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.

in this case one should use random.randint() in order to get equal distribution (i.e. given the required probability of 1/6).