Skip to content
Advertisement

How to change 12 random 0 to 1 in python Matrix

My program is suppose to change 12 zeros on random positions to 1 in python 6×6 matrix. This is my code.

from random import randint
M = []
i = 0

for i in range(6):
    M.append([])
    for j in range(6):
        M[i].append(0)

while i < 12:
    index = randint(0,5)
    index2 = randint(0,5)
    if (M[index][index2] == 0):
        M[index][index2] = 1
    i+=1

print(M)

So my matrix is going to look like this at the beggining

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

So I randomly chose an array and the element in chosen array. The problem is that different number of zeros is changed every time. Not 12 like I want them to change. Does anyone know how to solve this problem?

Advertisement

Answer

So you have two issues with your code. First off, you use the variable i in your for loop. By the time that’s finished running, Python has stored the variable and assigned the value 5 to it. So when you run your while-loop, you’re instead starting at 5 rather than zero like how you would like. A simple fix would be to use a different variable or assign i=0 again.

The second problem is your if statement and i+=1. This makes your while loop subject to repeating probabilities, with a 1/36 chance of having only 1 zero change! Including the i+=1 statement inside the if statement should fix your issue.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement