Home > database >  How to count how many times I got the certain result
How to count how many times I got the certain result

Time:10-21

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

CodePudding user response:

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.

CodePudding user response:

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)
  • Related