我正在尝试编写一个代码来划分以二进制形式给出的两个多项式(分别为newdata和proofin)。但是,当我运行代码时,我得到:
IndexError: index 0 is out of bounds for axis 0 with size 0
这是代码:
import numpy as np
def transformation_for_numpy_of_o():
newdata = ("101001")
freshdata = list(newdata)
freshdatapoly = []
for n in freshdata:
if n == 1:
freshdatapoly.append(1.0)
if n == 0:
freshdatapoly.append(0.0)
freshdatapoly = np.array(freshdatapoly)
return freshdatapoly
def transformation_for_numpy_of_proof():
proofin = ("101001")
proofing = list(proofin)
proofpoly = []
for n in proofing:
if n == 1:
proofpoly.append(1.0)
if n == 0:
proofpoly.append(0.0)
proofpoly = np.array(proofpoly)
return proofpoly
def total():
# Based on http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.polydiv.html
o_transformed = transformation_for_numpy_of_o()
proof_transformed = transformation_for_numpy_of_proof()
numer = np.array(o_transformed)
denomin = np.array(proof_transformed)
answer = np.polydiv(numer, denomin)
print (answer)
total()
我是numpy的新手并且不理解这个错误。我该如何解决这个问题?
*编辑:完整回溯,按要求:
/Users/M/anaconda/envs/Invictus/bin/python/Users/Max/PycharmProjects/1/Origin
Traceback (most recent call last):
File "/Users/M/PycharmProjects/1/Origin", line 49, in <module>
total()
File "/Users/M/PycharmProjects/1/Origin", line 46, in total
answer = np.polydiv(numer, denomin)
File "/Users/M/anaconda/envs/Invictus/lib/python3.5/site-packages/numpy/lib/polynomial.py", line 895, in polydiv
w = u[0] + v[0]
IndexError: index 0 is out of bounds for axis 0 with size 0
Process finished with exit code 1
答案 0 :(得分:2)
您正在比较整数和字符串,因此您的if永远不会评估为True,因此当proofpoly
同样适用于np.array(proofpoly)
时,freshdatapoly
始终为空:
更改新数据和校对:
freshdata = map(int,"101001")
proofing = list(map(int,"101001"))
由于您创建它们,只需将每个列表设为整数:
import numpy as np
def transformation_for_numpy_of_o():
freshdata = [1,0,1,0,0,1]
freshdatapoly = []
for n in freshdata:
if n == 1:
freshdatapoly.append(1.0)
if n == 0:
freshdatapoly.append(0.0)
return np.array(freshdatapoly)
def transformation_for_numpy_of_proof():
proofing = [1, 0, 1, 0, 0, 1]
proofpoly = []
for n in proofing:
if n == 1:
proofpoly.append(1.0)
if n == 0:
proofpoly.append(0.0)
return np.array(proofpoly)
现在,当你运行它时,你会得到一个结果:
In [2]: total()
(array([ 1.]), array([ 0.]))
也许还有更多我们看不到但目前代码相当于:
def transformation_for_numpy_of_o():
freshdata = [1,0,1,0,0,1]
return np.array(freshdata)
def transformation_for_numpy_of_proof():
proofing = [1, 0, 1, 0, 0, 1]
return np.array(proofing)
如果还有其他可能的值,您仍然可以使用列表comp:
def transformation_for_numpy_of_proof():
proofing = [1, 0, 4,5,1, 0, 0, 1, 4,3,5]
return np.array([i for i in proofing if i in {1,0}])