python - 在Python中创建具有特定条件的矩阵

标签 python arrays

我想知道存在多少个二元方阵,条件是每行和每列有两个,并且主对角线的元素为零。 我想创建一个程序,根据给定的矩阵大小,计算满足这些条件的数量。

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

相关文章:

python - Flask-RESTful - 上传图片

python - 获取所有相关的 Django 模型对象

java - 有没有办法将 "continue"放入 foreach 数组列表中

c++ - 构造函数中的数组设置意味着稍后失败

带标签的javascript多维数组

python - 解析字典中的文本并分成键和值

android - 从 SL4A 脚本启动 SL4A 脚本

python - 如何使用 python 在谷歌搜索中提取描述?

php - 引用返回的数组值的好习惯

c - 将字符分配给在 C 中使用 malloc 声明的二维数组时收到警告