Search code examples
pythonpython-3.xstringrandom

How can I check the probabilities of printing variables with random and count its frequency?


I would like to check/test the print probabilities of the three variables (separate and taken individually),

for example i would like to take many random draws and count the frequency of each value, or something similar. How can I?

import random

a = "Word A1", "Word A2", "Word A3", "Word A4"

b = "Word B1", "Word B2", "Word B3", "Word B4"

c = "Word C1", "Word C2", "Word C3", "Word C4"


a_random = random.choice(a)
b_random = random.choice(b)
c_random = random.choice(c)

sentence = a_random + ", " + b_random + ", " + c_random

print(sentence)

Solution

  • for example i would like to take many random draws and count the frequency of each value, or something similar. How can I?

    The simplest way to do that would be to write a loop and count how often each random draw occured. Example:

    import random
    from collections import Counter
    
    a = "Word A1", "Word A2", "Word A3", "Word A4"
    
    b = "Word B1", "Word B2", "Word B3", "Word B4"
    
    c = "Word C1", "Word C2", "Word C3", "Word C4"
    
    a_counter = Counter()
    for i in range(1000):
        a_random = random.choice(a)
        a_counter[a_random] += 1
    
    b_counter = Counter()
    for i in range(1000):
        b_random = random.choice(b)
        b_counter[b_random] += 1
    
    c_counter = Counter()
    for i in range(1000):
        c_random = random.choice(c)
        c_counter[c_random] += 1
    
    print(a_counter)
    print(b_counter)
    print(c_counter)
    

    The output shows how many times each word is selected.

    Counter({'Word A1': 252, 'Word A4': 251, 'Word A2': 251, 'Word A3': 246})
    Counter({'Word B1': 265, 'Word B4': 265, 'Word B3': 250, 'Word B2': 220})
    Counter({'Word C1': 266, 'Word C3': 264, 'Word C4': 236, 'Word C2': 234})