python - 在 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
解决方案
随机是正确的-正如评论的那样,这是一个数学问题:
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))
推荐阅读
- javascript - “您当前未连接到受支持的页面或应用程序。” 在 Internet Explorer 11 控制台中执行 JQuery 代码时出错
- c# - 如何从 ArrayList 或 GridView c# 中删除列
- javascript - 基于字段从数组中获取javascript对象
- cassandra - 无法让 Xandra 与 Cassandra 3 一起运行
- java - 为什么这个打印只有“假”而不是“假假”?
- java - Spring IoC:使用构造函数自动装配进行空检查的原因
- java - FIPS 加密策略 API
- excel - Excel 宏数据从一个工作簿传输到另一个工作簿
- c# - Unity3d暂停按钮不会暂停游戏onClick()
- jmeter - Jmeter 下载库 cmdrunner 失败