当我创建代码以使其输入“ Pin”并且代码尝试对其进行解码时,我编写了代码来解决此问题,但是它循环了太多次,因此我尝试用此方法将其缩短。 / p>
import numpy as np
print('enter your pin')
p = [
[int(input())],
[int(input())],
[int(input())],
[int(input())]
]
x = [
[0],
[0],
[0],
[0]
]
np_X = np.array(x)
y = [
[1],
[1],
[1],
[1]
]
np_Y = np.array(y)
while np_X.all(np_X) != p:
np_X = np_X + np_Y
print(np_X)
但是它给了我error
,我尝试自己解决,但是我得到的只是
TypeError:只能将整数标量数组转换为标量索引。
我想知道我在做错什么。
答案 0 :(得分:1)
np_X
是一个(4,1)数组:
In [114]: np_X
Out[114]:
array([[0],
[0],
[0],
[0]])
这是生成错误的代码。您应该已经显示了整个追溯。它可以帮助我们和您确定问题出在哪里。
In [115]: np_X.all(np_X)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-115-a3b876cb154f> in <module>
----> 1 np_X.all(np_X)
/usr/local/lib/python3.6/dist-packages/numpy/core/_methods.py in _all(a, axis, dtype, out, keepdims)
46
47 def _all(a, axis=None, dtype=None, out=None, keepdims=False):
---> 48 return umr_all(a, axis, dtype, out, keepdims)
49
50 def _count_reduce_items(arr, axis):
TypeError: only integer scalar arrays can be converted to a scalar index
查看numpy
all
的文档。它需要一个axis
参数,而不是数组!
有效用途是:
In [116]: np_X.all(0)
Out[116]: array([False])
In [117]: np_X.all(1)
Out[117]: array([False, False, False, False])
您想做什么?将p
与np_X
进行比较?
In [119]: np_X != p
Out[119]:
array([[ True],
[False],
[ True],
[ True]])
将all
方法应用于该布尔数组:
In [120]: (np_X != p).all()
Out[120]: False
使数组(4,1)形状(列向量)是不必要的复杂操作。一个简单的4元素数组就足够了:
In [121]: np_X = np.zeros(4, int)
In [122]: np_X
Out[122]: array([0, 0, 0, 0])
p = [
int(input()),
int(input()),
int(input()),
int(input())
]
或简单地:
p = [int(input()) for _ in range(4)]
答案 1 :(得分:0)
将您的while循环更改为此。
while not np.all(np_X == p):
np_X = np_X + np_Y
print(np_X)
但是,您的整个代码仍然无法正常工作。您正在向 x的每个元素加1。相反,您似乎想要遍历4个整数0-9的所有可能组合。
即。
from itertools import combinations
for pin_1, pin_2, pin_3, pin_4 in combinations(range(9), 4):
np_X = np.array([[pin_1], [pin_2], [pin_3], [pin_4]])
if np.all(np_X == p):
break
print(np_X)
答案 2 :(得分:0)
在这一行:
while np.all(np_X != p)
您正在打印
while np_X.all(np_X) != p: