0

I want to create a fishing game. Whenever the player press a button, the game will return a fish. Every fish has a percentage ( small fish , 45% ; medium fish, 25% ; big, 15%; huge, 4.9%; shark,0.1).

fish_size = [("small",45),("medium",25),("big",15),("huge",4.9),("shark",0.1)]

How can I get a fish randomly from this list by percentage?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
zewutz
  • 31
  • 7

2 Answers2

2

If you have a list of elements to choose from (in your case, the fish types), and a list of the weights (does not have to be normalised to 1 or 100%), you can use the choices method of the random built-in package. See its documentation for more detail.

An example:

>>> import random
>>> fish = ['small', 'medium', 'big', 'huge', 'shark']
>>> weights = [45, 25, 15, 4.9, 0.1]
>>> random.choices(fish, weights)[0]
'medium'

Note that you can use choices to return multiple elements (using the optional k keyword argument). Therefore, choices returns a list. By default, k=1, so only one value is returned in the list. Adding [0] to the end of the function call automatically extracts this value from the list.

luuk
  • 1,630
  • 4
  • 12
-1

You could do following:


fish_size = [("small",45),("medium",25),("big",15),("huge",5),("shark",1)]
helper = []
for x in fish_size:
    for y in range(x[1]):
        helper.append(x[0])

rand = random.randint(0, len(helper)-1)

print(helper[rand])

return for example

small

The only thing is, you can't use float percentages like 0.1, but other than that it works well. It works because the higher the percentage is, the more elements from it are in the helper list. If you then get a rand, the probability is higher if the percentage is higher

jonas
  • 122
  • 9