0

There is a list with float values, which can differ or not. How can I find the randomly chosen list-index of one of the highest values in this list?

If the context is interesting to you: I try to write a solver for the pen&paper game Battleship. I attempt to calculate probabilities for a hit on each of the fields and then want the the solver to shoot at one of the most likely spots, which means retrieving the index of the highest likelyhood in my likelyhood-list and then tell the game engine this index as my choice. Already the first move shows that it can happen, that there are a lot of fields with the same likelyhood. In this case it makes sense to choose one of them at random (and not just take always the first or anything like that).

erikbstack
  • 12,878
  • 21
  • 81
  • 115
  • 1
    What defines a high value? Also an example would be nice. – jamylak Apr 09 '12 at 14:25
  • Am I missing something here? Iterate through the list and keep track of the max value and index of the max value, or update a max variable as they're added to the list. – smcg Apr 09 '12 at 14:25

1 Answers1

4

Find the maximum using How to find all positions of the maximum value in a list?. Then pick a random from the list using random.choice.

>>> m = max(a)
>>> max_pos = [i for i, j in enumerate(a) if j == m]
>>> random.choice(max_pos)
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005