在Python中生成二维数组的置换矩阵

时间:2018-04-12 14:41:18

标签: python arrays matrix permutation

我想为输入d(这是一个素数)生成所有的平方置换矩阵。我知道有一些关于如何对所有排列做一般的例子,但我正在寻找满足数学定义的排列矩阵;

置换矩阵是通过根据数字1到d的某些排列来置换dxd 同一性矩阵的行而获得的矩阵。因此,每个行和列恰好包含单个1,其他地方都包含0。

例如对于2x2,[[1,0],[0,1]]和[[0,1],[1,0]]满足此要求,而[[1,1],[0,0] ]等等......不,所以我希望这不是一个重复的问题。我有一个代码,这样做,我的测试是我应该有!矩阵。当我到11岁时,我应该得到11!矩阵,但我得到的错误是我的代码由于内存丢失而关闭。我希望有人能够更有效地解决这个问题,因为我想要更大的素数;

import math
import numpy as np
import cmath
from sympy.utilities.iterables import multiset_permutations
from itertools import permutations, chain
from pprint import pprint
from numpy import ndarray
from numpy import linalg as LA


d=5
print("Prime dimension",d)
a=[1]+[0 for _ in range(d-1)]
N=[] 
P=[]
Pdagger=[]
for p in multiset_permutations(a):
    N.append(p)

#Generate a list of ALL the permutation matrices including Identity (last)
for n in multiset_permutations(N):
    n
    P.append(n)
print(len(P))

如果有帮助,我在IPython Jupyter笔记本中运行我的代码。我知道这可能不是最好/最有效的方式来运行这个,但我正在寻找任何人都可以给我的建议。顶部导入的所有库以后都与代码相关。

1 个答案:

答案 0 :(得分:0)

评论太大了。以下是我的想法:

import itertools

def I(n):
    A = []
    for i in range(n):
        A.append([1 if j == i else 0 for j in range(n)])
    return A

#tests:

A = I(3)

for m in itertools.permutations(A):
    print('\n'.join(str(row) for row in m))
    print('')

A = I(11)
count = 0
for m in itertools.permutations(A):
    count = count + m[0][0] #for testing purposes
print(count)

输出:

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

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

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

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

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

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

3628800

这需要大约10秒钟才能运行,最终的数字是11!/ 11(这是有意义的)。