首页 > 解决方案 > 在 Python 中创建具有特定条件的矩阵

问题描述

我想知道存在多少平方二进制矩阵,条件是它们每行和每列有两个,此外主对角线的元素为零。我想创建一个程序,给定矩阵的大小,计算有多少满足这些条件。

这是我目前一直在做的事情,但没有得出正确的计算结果。在 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

标签: pythonarrays

解决方案


随机是正确的-正如评论的那样,这是一个数学问题:

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))

推荐阅读