I am creating a matrix with this
def letsplay(m,n):
matrix = [[ '.' for m in range(10)] for n in range(10)]
for sublist in matrix:
s = str(sublist)
s = s.replace('[', '|').replace(']', '|').replace(',', "")
print(s)
that returns
>>> '.'.'.'.'.'.'.'.'.'.'
'.'.'.'.'.'.'.'.'.'.'
...
...
That creats a matrix 10x10. and Now I want to add within the matrix to random position with a probability = prob, the prob should be entered by the user, and return for the random posstions a 'N'.
How about using a probability matrix:
probs = numpy.random.random_sample((10, 10))
data = numpy.empty(probs.shape, dtype='S1')
data.fill('.')
data[probs < threshold] = 'N'
where threshold
is a variable that you choose, for example, 0.05 for a 5% chance.
Not quite sure what prob=5 would mean, probabilities range from 0 to 1?
I think there's two parts to your question.
change a random element of the matrix
matrix[random.randrange(10)][random.randrange(10)] = 'N'
have a number of elements changed in the matrix, based on a probability.
import random
prob = 0.01
numNs = prob*10*10 # because e.g. 1% chance in 10x10 matrix = 1 field
for i in range(numNs):
changed = False
while not changed:
x = random.randrange(10)
y = random.randrange(10)
if not matrix[x][y] == 'N': # if not already changed
matrix[x][y] = 'N'
changed = True