所以我试图检查是否在所有可能的排列之一上我会得到矩阵对角占主导地位的形式,但是当尝试检查它时我得到了一个错误

import numpy
from itertools import product
A = numpy.array([[10., -1., 2., 0.],
    [2., -1., 10., -1.],
    [-1., 11., -1., 3.],
    [0.0, 3., -1., 8.]])

def dominance(A):
    dominance=True
    n=4
    sumC=numpy.sum(numpy.absolute(A),axis=0)
    sumR=numpy.sum(numpy.absolute(A),axis=1)
    resC = [0 for i in range(n)]
    resR= [0 for i in range(n)]
    for i in range(n):
        resC[i]=sumC[i]-A[i,i]
        resR[i]=sumR[i]-A[i,i]
        if A[i,i]<resC[i] or A[i,i]<resR[i]:
            dominance=False
            break

    return dominance

def permutate(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)


if dominance(A):
    print "Es dominante"
else:
    for i in permutate(A):
        if dominance(list(i)):
            print "this way is dominant"
            print i
            break


这是错误

Traceback (most recent call last):
    File "Prueba.py", line 37, in <module>
        if dominance(list(i)):
    File "Prueba.py", line 16, in dominance
        resC[i]=sumC[i]-A[i,i]
TypeError: list indices must be integers, not tuple

最佳答案

您将A定义为列表列表。当您将其传递给dominance时,会出现此错误:

In [87]: dominance(A)
---------------------------------------------------------------------------
...
      8         for i in range(n):
----> 9                 resC[i]=sumC[i]-A[i,i]
     10                 resR[i]=sumR[i]-A[i,i]
     11                 if A[i,i]<resC[i] or A[i,i]<resR[i]:

TypeError: list indices must be integers, not tuple


但是,如果首先将A设置为数组,则运行良好:

In [94]: dominance(np.array(A))
Out[94]: False


我不会深入探讨为什么dominance会出现问题,但是看起来dominance是在考虑numpy数组而不是列表列表的情况下编写的。 sumC=numpy.sum(numpy.absolute(A),axis=0)A视为数组(它与列表A一起使用,因为内部absolute将其转换为数组)。

dominance的第二次调用还必须获得一个数组:

dominance(np.array(i))

09-25 20:19