Python Forum
Using Dictionary to Test Evenness of Distribution Generated by Randint Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Dictionary to Test Evenness of Distribution Generated by Randint Function
#4
(Feb-21-2021, 04:09 PM)new_coder_231013 Wrote: I'm trying to learn Python and am currently about halfway through an introductory book in
Also as new user you should not use Python 2.7,which as of Jan 2020 is officially dead💀
Code will give errors on print and has_key(removed) in Python 3.
So if fix indentation and write code so it work for Python 3.9 it look like this.
from random import randint

frequency = {}
for i in range(1000):
     num = randint(1, 10)
     if num in frequency:
          frequency[num] = frequency[num] + 1
     else:
        frequency[num] = 1

print(frequency)
Also a alternative is to use collections defaultdict as it's made for these kind of task.
import collections
from random import randint

frequency = collections.defaultdict(int)
for i in range(1000):
    frequency[randint(1, 10)] += 1

print(frequency)
Output:
defaultdict(<class 'int'>, {7: 99, 3: 98, 2: 98, 1: 105, 8: 92, 9: 103, 5: 111, 10: 101, 4: 106, 6: 87})
Can throw in Counter,to get most common.
>>> from collections import Counter
>>> 
>>> d = Counter(frequency)
>>> d.most_common(3)
[(5, 111), (4, 106), (1, 105)]
>>> d.most_common(1)
[(5, 111)]
Reply


Messages In This Thread
RE: Using Dictionary to Test Evenness of Distribution Generated by Randint Function - by snippsat - Feb-21-2021, 06:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  distribution fit Glaucio 1 277 Apr-07-2024, 12:30 AM
Last Post: Larz60+
  Weight Distribution 11drk9 11 805 Mar-13-2024, 06:08 AM
Last Post: Pedroski55
  random numbers, randint janeik 2 603 Nov-27-2023, 05:17 PM
Last Post: janeik
  Unexpected output while using random.randint with def terickson2367 1 557 Oct-24-2023, 05:56 AM
Last Post: buran
Information Best distribution method inovermyhead100 0 594 Jul-19-2023, 07:39 AM
Last Post: inovermyhead100
  HOW TO USE C# GENERATED DLL davide_vergnani 2 1,717 Jun-12-2023, 03:35 PM
Last Post: davide_vergnani
  passing dictionary to the function mark588 2 1,028 Dec-19-2022, 07:28 PM
Last Post: deanhystad
  How do I use a whl puython distribution? barryjo 6 1,847 Aug-15-2022, 03:00 AM
Last Post: barryjo
Sad Iterate randint() multiple times when calling a function Jake123 2 2,113 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  How to test and import a model form computer to test accuracy using Sklearn library Anldra12 6 3,219 Jul-03-2021, 10:07 AM
Last Post: Anldra12

Forum Jump:

User Panel Messages

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