Reputation: 39
I have this mathematical problem where I need to select a random element from a matrix. Now I have the code for the matrix and other bits. but I tried to select a random element by using below code but It always selects one complete row, instead of a random single element.
def randSelect(self):
return self.matrix[random.randrange(len(self.matrix))]
Here is the complete code as well
class Matrix():
def __init__(self, cols, rows):
self.cols = cols
self.rows = rows
self.matrix = []
for i in range(rows):
selec_row = []
for j in range(cols):
selec_row.append(0)
self.matrix.append(selec_row)
def setitem(self, col, row, v):
self.matrix[col-1][row-1] = v
def randSelect(self):
return self.matrix[random.randrange(len(self.matrix))]
def __repr__(self):
outStr = ""
for i in range(self.rows):
outStr += 'Row %s = %s\n' % (i+1, self.matrix[i])
return outStr
a = Matrix(3,3)
a.setitem(1,2,10)
a.setitem(1,3,15)
a.setitem(2,1,10)
Upvotes: 0
Views: 1106
Reputation: 4158
Here is my solution. I am using a namedtuple as the return so you can get the position of that value as well.
import random
from collections import namedtuple
RandomValue = namedtuple("RandomValue", ("Value", "RowIndex", "ValueIndex"))
class Matrix():
def __init__(self, cols, rows):
self.cols = cols
self.rows = rows
self.matrix = []
for i in range(rows):
selec_row = []
for j in range(cols):
selec_row.append(0)
self.matrix.append(selec_row)
def setitem(self, col, row, v):
self.matrix[col - 1][row - 1] = v
def randSelect(self):
row = self.matrix[random.randrange(len(self.matrix))]
value = random.choice(row)
return RandomValue(value, self.matrix.index(row), row.index(value))
def __repr__(self):
outStr = ""
for i in range(self.rows):
outStr += 'Row %s = %s\n' % (i + 1, self.matrix[i])
return outStr
a = Matrix(3, 3)
a.setitem(1, 2, 10)
a.setitem(1, 3, 15)
a.setitem(2, 1, 10)
print(random_val.RowIndex)
print(random_val.ValueIndex)
print(random_val.Value)
Upvotes: 1
Reputation: 142631
def randSelect(self):
row = random.randrange(self.rows)
col = random.randrange(self.cols)
return self.matrix[row][col]
Upvotes: 3
Reputation: 698
you can have a function generate random numbers in the range of your indices and you can use those indices to call a random location in your array
from random import randint
i = (randint(0,9)) #assuming your range for i is from 0-9
j = (randint(0,9)) #assuming your range for j is from 0-9
Upvotes: 0
Reputation: 7347
Your randselect
function needs to access self.matrix
with two indices. It's an array of arrays, so with only one set of square brackets you get back an array. You'll need a second access to get an individual element.
def randSelect(self):
row = self.matrix[random.randrange(len(self.matrix))]
return row[random.randrange(len(row))]
Upvotes: 0