0

I have the following code for a two-player game using nashpy. When I calculate my support enumeration it comes back with a list of arrays. How do I randomly choose an array from this list?

For example, when my list is this:

[(array([1., 0.]), array([0., 1.])), (array([0., 1.]), array([1., 0.])), (array([0.5, 0.5]), array([0.66666667, 0.33333333]))]

...I wish to randomly take one array from this list such as [0.66666667, 0.33333333].

How do I go by doing this.?

My code:

import numpy as np
import nashpy as nash
import random


A = np.array([[1, 2], [2, 0]])
B = np.array([[0, 1], [0, -1]])
game = nash.Game(A,B)
print(game)
eqs = game.support_enumeration() 
 
a = list(eqs)
b = random.choices(a)
kill wind
  • 1
  • 3
  • Does this answer your question? [How can I randomly select an item from a list?](https://stackoverflow.com/questions/306400/how-can-i-randomly-select-an-item-from-a-list) – Code-Apprentice Dec 06 '21 at 00:53
  • In the future, I encourage you to google for the answer. For example, "python random choice from list" gives lots of hits taht show how to do this. – Code-Apprentice Dec 06 '21 at 00:54

2 Answers2

0

Super close! You can just call random.choice(a) where you have random.choices(a), which should work on any list.

Another way to go about would be to generate a random number between 0 and the length of your list and index your list with that random number.

For clarity:

import random

>>> y  = [(array([1., 0.]), array([0., 1.])), (array([0., 1.]), array([1., 0.])), (array([0.5, 0.5]), array([0.66666667, 0.33333333]))]
>>> random.choice(random.choice(y))
array([0.5, 0.5])
  • This won't work. `eqs` is actually a list of tuples, where each tuple contains two numpy arrays. The OP wants any one of these numpy arrays. –  Dec 06 '21 at 00:39
  • So just wrap it in another random choice? It is the solution – lunastarwarp Dec 06 '21 at 00:44
0

Try this:

eqs = game.support_enumeration()
a = np.reshape(np.array(list(eqs)), (-1, 2))
b = random.choice(a)