gpt4 book ai didi

python - 在Python中生成二维数组的排列矩阵

转载 作者:行者123 更新时间:2023-12-01 09:32:57 24 4
gpt4 key购买 nike

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

置换矩阵是通过根据数字 1 到 d 的某种排列对 dxd 恒等矩阵的行进行置换而获得的矩阵。因此,每个行和列都精确地包含一个 1,其他地方都包含 0。

例如,对于 2x2,[[1,0],[0,1]] 和 [[0,1],[1,0]] 满足这一点,而 [[1,1],[0,0] ] 等...不,所以我希望这不是一个重复的问题。我有一个代码可以做到这一点,我的测试是我应该有 d!矩阵。当我到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 笔记本中运行我的代码。我知道这可能不是最好/最有效的运行方式,但我正在寻找任何人可以给我的建议。顶部导入的所有库都与后面的代码相关。

最佳答案

太大,无法发表评论。这是我想到的事情:

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(这是有道理的)。

关于python - 在Python中生成二维数组的排列矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com