0

I need to randomly choose a tuple from a list of tuples given probabilities to be chosen for each tuple.

I'm trying the following code:

from numpy.random import choice
v = [(0, 0), (0, 1), (1, 0), (1, 1)]
pr = [0.3, 0.2, 0.1, 0.4]
print(choice(v, p=pr))

However, I get this message: ValueError: a must be 1-dimensional

How can fix that issue?

alekscooper
  • 795
  • 1
  • 7
  • 19

3 Answers3

1

You could try the same with the random module and the "weights" parameter:

import random
v = [(0, 0), (0, 1), (1, 0), (1, 1)]
pr = [0.3, 0.2, 0.1, 0.4]
print(*random.choices(v, weights=pr))

If you still need a numpy array, you can create it after getting the random tuple:

import random
import numpy as np

v = [(0, 0), (0, 1), (1, 0), (1, 1)]
pr = [0.3, 0.2, 0.1, 0.4]
rand_pr = np.array(*random.choices(v, weights=pr))
print(rand_pr)
Isma
  • 14,604
  • 5
  • 37
  • 51
0

Convert items of v from tuple to str which is one-d object

from numpy.random import choice

v = [(0, 0), (0, 1), (1, 0), (1, 1)]
pr = [0.3, 0.2, 0.1, 0.4]
print(choice(list(map(str, v)), p = pr))

Method-2

from numpy.random import choice

ind = list(range(4))
v = [(0, 0), (0, 1), (1, 0), (1, 1)]
pr = [0.3, 0.2, 0.1, 0.4]
print(v[choice(ind, p = pr)])
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22
0

your v has to be 1-D array-like or int as a workaround you can make a list of indexes of your v list, randomly chose an index and print v[index]

from numpy.random import choice
v = [(0, 0), (0, 1), (1, 0), (1, 1)]
a = [0,1,2,3]
pr = [0.3, 0.2, 0.1, 0.4]
print(v[(choice(a, p=pr))])

or for more universal usage:

from numpy.random import choice
v = [(0, 0), (0, 1), (1, 0), (1, 1)]
a = []
for i in range (0,len(v)):
    a.append(i)
pr = [0.3, 0.2, 0.1, 0.4]
print(v[(choice(a, p=pr))])
bukszpryt
  • 23
  • 4