a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
def dirReduc(arr):
index = int(0)
for i in arr:
for j in arr:
if (len(arr[index]) == len(arr[index + 1])) and (arr[index] != arr[index + 1]):
arr.pop(index)
arr.pop(index)
index = 0
else:
index += 1
print(arr)
dirReduc(a)
此代码的目的是减少彼此相邻的相反方向。而我的吡喃给了我正确的输出,没有任何错误,即:
arr = ["WEST"]
在它应该编译的codewars网站上,我通过了所有的测试,但是这个站点给了我:
IndexError:列出超出范围的索引
有什么简单的方法来处理这个错误,让它在代码战中工作吗?
发布于 2017-10-01 09:45:22
不是排除另一种方法,而是在遍历原始数组的同时组装一个新数组:
a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
opposite = {"NORTH": "SOUTH", "SOUTH": "NORTH", "WEST": "EAST", "EAST":"WEST"}
def dirReduc(arr):
if not arr:
return []
b=[]
i = 0
while i < len(arr):
if i == len(arr)-1:
b = b+[arr[i]]
break
else:
if arr[i+1] == opposite[arr[i]]:
i = i+2
else:
b=b+[arr[i]]
i = i+1
return b
reduced_a = a
while True:
reduced_b = dirReduc(reduced_a)
if reduced_b == reduced_a:
reduced_a = reduced_b
break
else:
reduced_a = reduced_b
print(dirReduc(reduced_b))
https://stackoverflow.com/questions/46510850
复制相似问题