整数值问题以及如何提供语法来描述 Python 中的 Int 值
Integers value problem and How to provide syntax to depicting Int value in Python
我目前遇到的错误描述为:仅整数、切片 (:
)、省略号 (...
)、numpy.newaxis (None
) 和整数或布尔数组是有效的索引。
我其实明白这个问题。但是我无法在 python 代码中修复它,因为我只是使用 Python 的初学者。
完整代码在 link: 'https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch9/TSP.py'
终端报告是:
((1, 2, 3, 4, 0), 2.4225597326923185)
0.0004763603210449219
Greedy search
Traceback (most recent call last):
File "TSP.py", line 183, in <module>
runAll()
File "TSP.py", line 167, in runAll
print (greedy(distances))
File "TSP.py", line 57, in greedy
dist[:,cityOrder[0]] = np.Inf
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
无效代码:
nCities = np.shape(distances)[0]
distanceTravelled = 0
# Need a version of the matrix we can trash
dist = distances.copy()
cityOrder = np.zeros(nCities)
cityOrder[0] = np.random.randint(nCities)
dist[:,cityOrder[0]] = np.Inf
for i in range(nCities-1):
cityOrder[i+1] = np.argmin(dist[cityOrder[i],:])
distanceTravelled += dist[cityOrder[i],cityOrder[i+1]]
# Now exclude the chance of travelling to that city again
dist[:,cityOrder[i+1]] = np.Inf
# Now return to the original city
distanceTravelled += distances[cityOrder[nCities-1],0]
return cityOrder, distanceTravelled ```
问题来自 numpy.zeros
(文档 here)的使用。可以看到,输出数组默认的dtype
是float
。而且你不能使用浮点数来索引数组。
快速解决方法是将 cityOrder
的 dtype
指定为 int
:
cityOrder = np.zeros(nCities, dtype=int)
我目前遇到的错误描述为:仅整数、切片 (:
)、省略号 (...
)、numpy.newaxis (None
) 和整数或布尔数组是有效的索引。
我其实明白这个问题。但是我无法在 python 代码中修复它,因为我只是使用 Python 的初学者。
完整代码在 link: 'https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch9/TSP.py'
终端报告是:
((1, 2, 3, 4, 0), 2.4225597326923185)
0.0004763603210449219
Greedy search
Traceback (most recent call last):
File "TSP.py", line 183, in <module>
runAll()
File "TSP.py", line 167, in runAll
print (greedy(distances))
File "TSP.py", line 57, in greedy
dist[:,cityOrder[0]] = np.Inf
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
无效代码:
nCities = np.shape(distances)[0]
distanceTravelled = 0
# Need a version of the matrix we can trash
dist = distances.copy()
cityOrder = np.zeros(nCities)
cityOrder[0] = np.random.randint(nCities)
dist[:,cityOrder[0]] = np.Inf
for i in range(nCities-1):
cityOrder[i+1] = np.argmin(dist[cityOrder[i],:])
distanceTravelled += dist[cityOrder[i],cityOrder[i+1]]
# Now exclude the chance of travelling to that city again
dist[:,cityOrder[i+1]] = np.Inf
# Now return to the original city
distanceTravelled += distances[cityOrder[nCities-1],0]
return cityOrder, distanceTravelled ```
问题来自 numpy.zeros
(文档 here)的使用。可以看到,输出数组默认的dtype
是float
。而且你不能使用浮点数来索引数组。
快速解决方法是将 cityOrder
的 dtype
指定为 int
:
cityOrder = np.zeros(nCities, dtype=int)