Search code examples
pythonnumpyrandomprobabilitygenerate

How can I get the program to ask user how many tries do they want to generate from a random pool of elements, each with different probabilities?


I am trying to create a piece of code that asks the user to input a desired amount of tries, for example: -How many do you want to generate? -Generate 5 random animals from a pool [Dog, Cat, Hippo, Panda].

  • Dog, Dog, Hippo, Dog, Cat

each animal has a different chance in the probability of showing up when it's generated. (see code below)


while True:
    option = input("Execute y/n")
    if option == 'y':
        animals = ['Dog', 'Cat', 'Hippo', 'Panda']
        weights = [0.5, 0.35, 0.1, 0.05]
        result = np.random.choice(animals, p=weights)
        print(result)
    else:
        break 

the problem with my code is that, it is not creating several tries and if I put, for example:

print(result*5) it prints the same result 5 times and not different results.


Solution

  • Here's a way to attack the problem with a list comprehension:

    import numpy as np
    
    animals = ['Dog', 'Cat', 'Hippo', 'Panda']
    weights = [0.5, 0.35, 0.1, 0.05]
    
    while True:
        count = int(input("How many (0 = exit) >"))
        if count <= 0:
            break
        result = [np.random.choice(animals, p=weights) for _ in range(count)]
        print(result)
    

    Result:

    How many (0 = exit) >7
    ['Dog', 'Hippo', 'Cat', 'Dog', 'Cat', 'Cat', 'Dog']
    How many (0 = exit) >12
    ['Cat', 'Dog', 'Cat', 'Panda', 'Panda', 'Hippo', 'Dog', 'Cat', 'Cat', 'Dog', 'Dog', 'Cat']
    How many (0 = exit) >3
    ['Dog', 'Dog', 'Hippo']
    How many (0 = exit) >0
    

    Dealing with non-numeric input left as an exercise for the OP.