Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python how to
#1
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.
Reply
#2
You'll want the random and collections modules.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
Use this to simulate a result of rolling:

import random
r = int(random.random()*6)
Reply
#5
(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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
(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).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020