0

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.

Strider
  • 19
  • 4
  • You could use a loop. E.g. `for i in range(5):` and put the code to select and print an animal inside that loop. – Nick ODell Oct 09 '22 at 00:13

1 Answers1

1

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.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44