在Hill-RSA密码术中,“TypeError:只能将整数标量数组转换为标量索引”

我正在尝试编写Hill-RSA加密程序,您可以在此处看到其中的一部分:

q2=31
alphabet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",","," ",".",";","_"]
X=np.zeros((m,1),dtype=np.int32)
Y=np.zeros((m,1),dtype=np.int32)
Texte_decode="";
for i in range(1,(len(Texte_code)/m)+1):
    for k in range(0,m):
        j=0
        while (Texte_code[k+m*(i-1)]<>alphabet[j+1]):
            j=j+1
        X[k]=j
    X=X.transpose()
    A2=np.zeros((m,m),dtype=np.int32)
    for u in range(0,m):
        for l in range(0,m):
            A2[u,l]=A[u,l]
    Y=X.dot(A2)
    Y=Y.transpose()
    pprint(Y)
    Y2=np.zeros((m,1),dtype=np.int32)
    for ind in range(0,m):
        Y2[ind]=Y[ind]%q2
    pprint(Y2)
    for k in range(0,m):
        Texte_decode=Texte_decode+alphabet[Y2[k]+1]
for i in range(len(Texte_decode),len(Texte_decode)-m+1,-1):
    if Texte_decode[i]=="." and Texte_decode[i-1]==".":
        Texte_decode=Texte_decode[1,i-1]
print Texte_decode

当我执行这部分时,我明白了

“TypeError:只能将整数标量数组转换为标量索引”

在线上

Texte_decode=Texte_decode+alphabet[Y2[k]+1]

任何人都可以帮我摆脱这个错误吗?

提前致谢

回答(1)

2 years ago

你做了什么调试?您是否已查看问题行元素的性质?

Texte_decode=Texte_decode+alphabet[Y2[k]+1]

k 来自 for k in range(0,m): 所以不应该't be the problem. It'显然是一个整数 .

你打印 Y2 . 它被初始化为 (m,1) 数组 . 所以 Y2[k] 将是一个(1,)数组,对吧?

alphabet 是一个清单 .

在交互式shell中,让我们尝试一个测试用例:

In [70]: [1,2,3,4][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-4ad73b219fa3> in <module>()
----> 1 [1,2,3,4][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

相同的错误消息!

如果我们从1d数组开始,并选择一个元素,索引工作:

In [71]: [1,2,3,4][np.arange(4)[1]]
Out[71]: 2

现在我们了解了问题,解决方案应该是显而易见的,对吧?