IndexError:数组反转中列表索引超出范围
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IndexError:数组反转中列表索引超出范围相关的知识,希望对你有一定的参考价值。
我正在尝试按组反转数组。我已经浪费了半个多小时来查找问题,但无法弄清楚索引超出范围的情况。这是我的代码:
def rev(A,S,N):
start=S
end=N
while start<end:
A[start],A[end]=A[end],A[start] #error here
start+=1
end-=1
return A
def reverseInGroups(A,N,K):
#Your code here
rev(A,0,K)
rev(A,K,N) #error here
return A
这是我得到的错误
答案
根本不需要使用/迭代位置:
def rev(data, start, end):
"""Reverses the range start:end (end exclusive) of the given list. No safeguards whatsoever
so only use with correct data. Out of bounds is irrelevant due to slices used to revers."""
data[start:end] = data[start:end][::-1] # you need end+1 if you want inclusive
return data
def reverseInGroups(A,N,K):
#Your code here
rev(A,0,K)
rev(A,K,N) #error here
return A
l = list(range(11))
print ( reverseInGroups(l , 8, 3)) # why N (the bigger number) first?
获取
2, 1, 0, 7, 6, 5, 4, 3, 8, 9, 10]
#0 1 2 3 4 5 6 7 8 9 10 # position in the list that got reversed: 3-7
另一答案
怎么样
def rev(a,start,end, middle):
assert 0 <= start <= middle <= end < len(a)
a[start:middle] = reversed(a[start:middle])
a[middle:end] = reversed(a[middle:end])
return a
以上是关于IndexError:数组反转中列表索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章
IndexError:Topcoder 提交中的列表索引超出范围
findspark.init() IndexError: 列表索引超出范围错误