Oleg Dats
Oleg Dats

Reputation: 4133

How to create a random matrix in Pure Python?

What is equivalent pure python code?

A = np.random.randint(2, size=(4,2))

array([[0, 1],
       [0, 1],
       [0, 0],
       [1, 0]])

Upvotes: 0

Views: 419

Answers (2)

totok
totok

Reputation: 1500

This could suit you.

from random import randint

A = [[randint(0, 1) for y in range(2)]   for x in range(4)]

print(A)

output:

>>> [[0, 0], 
     [0, 0],
     [0, 1],
     [0, 1]]

Upvotes: 4

Yehya Chali
Yehya Chali

Reputation: 26

if you need different shapes with multiple dimensions here it is the code:

import random

def random_matrix(c,shape):
    for i in range(len(shape)):
        if len(shape)-i>1:
            for j in range(shape[i]):
                return [random_matrix(c,shape[i+1:]) for b in range(shape[i])]
        else:
            return [random.randint(0,c-1) for v in range(shape[i])]

mat = random_matrix(2,[3,3,1])
print(mat)
print(mat[0])

Output:

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

or just as in your example:

mat = random_matrix(2, [4,2])
print(mat)

output:

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

Upvotes: 0

Related Questions