1

I am trying to write a code that would select 5 numbers between 1-10 and choose the maximum of them. I repeat the experiment 1000 times but I want to see how many times ı get the which result

import random
for i in range (1,1000):
    b = random.choices(range(1, 11), k=5)
    max(b)
    print("The X value for %(n)s is {%(c)s} " % {'n': b, 'c': max(b)})

I want to see something like 10 occurring 500 times, 9 occurring 300 times. I tried to define a dictionary but couldn't manage to do so. Any help would be appreciated

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25

4 Answers4

2

Use defaultdict.

import random
from collections import defaultdict

counter = defaultdict(int)
for i in range(1, 1000):
    numbers = random.choices(range(1, 11), k=5)
    counter[max(numbers)] += 1
print(counter)

Output:

defaultdict(<class 'int'>, {10: 406, 8: 161, 9: 269, 7: 86, 6: 40, 5: 25, 4: 10, 3: 2})
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
balderman
  • 22,927
  • 7
  • 34
  • 52
2

You can use Counter and a generator expression like this:

from collections import Counter
Counter(max(random.choices(range(1, 11), k=5)) for _ in range(1, 1000))

Example output:

Counter({10: 388, 9: 281, 8: 161, 7: 91, 6: 41, 5: 23, 4: 10, 3: 4})
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
bitflip
  • 3,436
  • 1
  • 3
  • 22
  • `dict(Counter(max(random.choices(range(1, 11), k=5)) for _ in range(1, 1000)))` to get a dict instead of a counter object – bitflip Oct 20 '22 at 19:42
1

You can create a dictionary with all the necessary keys, and then add 1 to the value each time that key comes up.

import random
number_counts = {x:0 for x in range(1,11)} # this will create a dictionary with 1-10 as keys and 0 as values
for i in range(1,1000):
    b = random.choices(range(1,11),k=5)
    m = max(b)
    number_counts[m] += 1

print(number_counts)
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
0

use the .count() method. Quite simple TBF. Here's how it works, in google's words.

The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.

jhdthelad
  • 1
  • 4
  • Credit for quote: https://datagy.io/python-count-occurrences-in-list/ – CrazyChucky Oct 25 '22 at 11:48
  • `count` is great for getting the count of just one value. For multiple values, it still works, but it has to iterate through the whole list again each time. – CrazyChucky Oct 25 '22 at 11:50