如何找到两个相等的 n 元组矩阵?

How to find two n-tuple matrices are equal?

提问人:Mershia Rabuni 提问时间:7/21/2022 最后编辑:M. JustinMershia Rabuni 更新时间:11/13/2023 访问量:54

问:

我试过这个程序

from pprint import pprint

m = int(input("Number of matrices: "))
rows = int(input("Enter the Number of rows : "))
columns = int(input("Enter the Number of Columns: "))

matrices = []
for i in range(m):
    print("Enter the elements of Matrix:")
    matrix_i = [[tuple(map(float, input().split(" "))) for c in range(columns)]
                for r in range(rows)]
    print("Matrix no: ", i + 1)
    for n in matrix_i:
        print(n)
    print()
    matrices.append(matrix_i)
pprint(matrices)

def areequal(A,B):   
    for i in range(rows):
        for j in range(columns):
            if (((A[i][j][0] ==  B[i][j][0]), (A[i][j][1] ==  B[i][j][1]), (A[i][j][2] ==  B[i][j][2]))):
                return 1
    return 0
for m1 in matrices:
    for m2 in matrices:
        if (areequal(m1, m2)==1):
            print(m1, m2)
            print("Matrices are identical")
        else:
            print(m1, m2)
            print("Matrices are not identical")

使以下矩阵的输出相同

m1=
[(1.0, 2.0, 3.0) (8.0, 7.0, 6.0)]
[(8.0, 7.0, 6.0) (4.0, 5.0, 6.0)]
m2 =
[(3.0, 4.0, 5.0) (9.0, 8.0, 7.0)]
[(3.0, 4.0, 5.0) (9.0, 8.0, 7.0)]
m3 =
[(0.0, 9.0, 7.0) (2.0, 3.0, 4.0)]
[(8.0, 7.0, 6.0) (8.0, 7.0, 6.0)]

例如,像这样

[[(0.0, 9.0, 7.0), (2.0, 3.0, 4.0)], [(8.0, 7.0, 6.0), (8.0, 7.0, 6.0)]] [[(3.0, 4.0, 5.0), (9.0, 8.0, 7.0)], [(3.0, 4.0, 5.0), (9.0, 8.0, 7.0)]]
Matrices are identical

[[(0.0, 9.0, 7.0), (2.0, 3.0, 4.0)], [(8.0, 7.0, 6.0), (8.0, 7.0, 6.0)]] [[(0.0, 9.0, 7.0), (2.0, 3.0, 4.0)], [(8.0, 7.0, 6.0), (8.0, 7.0, 6.0)]]
Matrices are identical

即使矩阵不相同/相等,输出也要相同。

为什么我让所有矩阵都相同?如何找到两个相等的 n 元组矩阵?如何找到给定的矩阵成对相等(如(m1和m2),(m2和m3),(m3和m1))?如何在没有重复的情况下获得结果(如(m1和m1),(m2和m2),(m3和m3))?

Python 矩阵 元组 相等

评论

1赞 cards 7/21/2022
旁注:在测试程序时,您可以使用打包并修复,而不是使用它可能会很烦人,这样您就可以重现相同的输出。如果它工作正常,则切换到inputrandomseedinput
0赞 Kelly Bundy 7/21/2022
避免正常检查的原因是什么?m1 == m2

答:

2赞 John Coleman 7/21/2022 #1

逗号创建元组,而不是布尔值。元组是真实的。生产线

if (((A[i][j][0] ==  B[i][j][0]), (A[i][j][1] ==  B[i][j][1]), (A[i][j][2] ==  B[i][j][2]))):

本质上是

if True:

相反,请使用

if (((A[i][j][0] ==  B[i][j][0]) and (A[i][j][1] ==  B[i][j][1]) and (A[i][j][2] ==  B[i][j][2]))):