Home > OS >  how to count a list of numbers which occour in a random list Python
how to count a list of numbers which occour in a random list Python

Time:10-28

I run 1000 times of random.choice()from a list from 0-11. how to track of the number of random selections necessary before all 12 number have been selected at least once. (Many will be selected more than once.) For instance, suppose the simulation yields the following sequence of random choices for a single trial: 2 5 6 8 2 9 11 10 6 3 1 9 7 10 0 7 0 7 4, where all 12 numbers have been selected at least once. The count for this example trial is 19. Collect the count for each trial of the simulation in a single list (ultimately consisting of 1,000 counts).

CodePudding user response:

Here is a solution using collections.Counter as a container:

from collections import Counter
import random

nums = list(range(12))
n = 1000
counts = [0]*n
for trial in range(n):
    c = Counter()
    while len(c)<len(nums):
        c[random.choice(nums)] =1
    counts[trial] = sum(c.values()) # c.total() in python ≥ 3.10

counts

Output:

[28, 24, 39, 27, 40, 36, ...] # 1000 elements

Distribution of the counts:

histogram of counts

CodePudding user response:

Maybe you can try using a set to store your results in a non-redundant way, while checking to see if all numbers have been used:

import random

guesses = set()
count = 0
for i in range(1000):
    count  = 1
    guesses.add(random.randrange(0, 12))
    if len(guesses) == 12:
        break
print(count)

This will give you 1 count. A better method is outlined by mozway in their answer.

You can run the code a million times and collect the results in a list, then graph it like so (updated with a while condition):

import random
import numpy as np
from matplotlib import pyplot as plt

counts = []
for i in range(100000):
    guesses = set()
    count = 0
    while len(guesses) != 12:
        count  = 1
        guesses.add(random.randrange(0, 12))

    counts.append(count)

fig = plt.figure(figsize=(8, 6))
x = np.array([i for i in range(np.max(np.array(counts)))])
y = np.array([counts.count(i) for i in range(np.max(np.array(counts)))])
plt.bar(x, y)
plt.xlabel('Number of Guesses')
plt.ylabel('Frequency')
plt.show()

enter image description here

So [counts.count(i) for i in range(np.max(np.array(counts)))] is going to give you a list of how often the guessing game finished for that given position of the list. I.e. the first value of the list is 0, because there is no way that the game can finish with only 1 guess, but at position 25 (25 guesses) there are over 2000 instances of that happening

CodePudding user response:

One simple (but inefficient) way to do this would be with

check = range(11)
if all(elem in randlist for elem in check): # check after each choice
    # do something

As others have said, tell us what you have tried so far so we can help further.

  • Related