简体   繁体   中英

Construct n x n matrix with unique value from 1 to n in Python

I have two lists in Python

P = [P1, P2..... Pn] , D = [D1, D2..... Dn] .

I want to create a matrix in such a way that each cell should contain a value from 1 to n . Cell value should be unique both in the row and column and each time it should generate different combination.

Sample output is shown below for n=3 and arbitrary P and D both of size 3.

Anyone has any idea of generating such matrix?

n x n 矩阵

You can do the following:

import random

def createMatrix(n):
    firstRow = random.sample(range(n),n)
    permutes = random.sample(range(n),n)
    return list(firstRow[i:]+firstRow[:i] for i in permutes)


N = 5
m = createMatrix(N)
print(m)

Which for the case of N=5 gives (after converting to numpy array for the printing):

[[4 0 1 2 3]
 [1 2 3 4 0]
 [3 4 0 1 2]
 [0 1 2 3 4]
 [2 3 4 0 1]]

In the case of values starting from 1 the correction to the function is:

def createMatrix(n):
    firstRow = random.sample(range(1, n + 1),n)
    permutes = random.sample(range(1, n + 1),n)
    return list(firstRow[i:]+firstRow[:i] for i in permutes)

Solution without modules and by pattern. You can input anything you want in P1, and will give you a matrix

P1 = list(range(1, 101))

matrix_len = len(P1)
w, h = matrix_len, matrix_len
matrix = [[None for x in range(w)] for y in range(h)]
counter=0
for i in range(matrix_len):
    for j in range(matrix_len):
        matrix[counter][j] = i
        counter +=1
        if counter == matrix_len:
            counter= 0
    counter +=1

print(matrix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM