我想知道存在多少个二元方阵,条件是每行和每列有两个,并且主对角线的元素为零。 我想创建一个程序,根据给定的矩阵大小,计算满足这些条件的数量。
这就是我目前一直在做的事情,但没有得出正确的计算结果。在 3x3 矩阵中,我得到 3 种可能性,但只有 1 种。我认为同一个矩阵被计算了多次。 我该怎么做? 谢谢
import numpy as np
def funcion(n):
total = 0
for i in range(n):
a = np.random.randint(0, 2, (n, n))
while a[i].sum() != 2 or a[:, i].sum() != 2 or a[i][i] != 0:
a = np.random.randint(0, 2, (n, n))
if a[i].sum() == 2 and a[:, i].sum() == 2 and a[i][i] == 0:
total = total + 1
print(total)
return total
最佳答案
随机是正确的 - 正如所评论的,这是一个数学问题:
def funcion(n):
# every row has n - 1 slots that can be filled with 1 as one must be 0
# (the diagonal) - we must pick exactly two slots
slots_with_one = (n - 1) * (n - 2) // 2
# now that we picked those in all other rows we must put a one on those
# columns exactly - if not that column won't have two ones, so we're done
return slots_with_one
print(funcion(3))
print(funcion(4))
print(funcion(5))
关于python - 在Python中创建具有特定条件的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58269531/