Python 未超索引情况下 显示 IndexError

Python 未超索引情况下 显示 IndexError

如下,我正在解 leetcode 第14题 找数组的最长公共前缀。

想法是先排序,找出最短的值,

然后循环最短值的长度次,然后再循环数组,对比最短值的索引和数组内其他值的索引是否相同.

不同就跳出循环返回最长公共前缀

不懂的是这里为什么会在未超索引的情况下显示 超索引呢?

代码如下

class Solution(object):

def longestCommonPrefix(self, strs):

strs.sort(key = len)

if len(strs) >= 2:

z = strs[0]

for i in range(len(z)):

for s in strs[1:]:

if z[i] != s[i]:

z = z[0:i]

break

else:

print(z[i], s[i], s, i, z)

return z if z else ''

elif len(strs) == 1:

return strs[0]

else:

return ''

s = Solution()

print(s.longestCommonPrefix(["flower","flow","flight"]))

报错如下:

f f flower 0 flow

f f flight 0 flow

l l flower 1 flow

l l flight 1 flow

o o flower 2 flow

Traceback (most recent call last):

File "C:\Users\Administrator\Downloads\shaoq.py", line 50, in <module>

print(s.longestCommonPrefix(["flower","flow","flight"]))

File "C:\Users\Administrator\Downloads\shaoq.py", line 38, in longestCommonPrefix

if z[i] != s[i]:

IndexError: string index out of range

[Finished in 1.1s]

但是同样的循环我测试了下在 powershell 里面是可以运行的,奇怪

>>> x = ["flower","flow","flight"]

>>> x.sort(key = len)

>>> x

['flow', 'flower', 'flight']

>>> z = x[0]

>>> for i in range(len(z)):

... for st in x[1:]:

... print(z[i], st[i])

...

f f

f f

l l

l l

o o

o i

w w

w g

>>> for i in range(len(z)):

... for st in x[1:]:

... if z[i] != st[i]:

... print(i, z[i], st[i], z[0:i])

...

2 o i fl

3 w g flo

等解答,谢谢~


回答:

你在 powershell 里没有 z = z[0:i] 啊 ....

z = z[0:i] 之后,z 变短了,然后 i 还在继续增加,增加到 z 原来的长度

要测试的话,就用原样的程序来测试。

以上是 Python 未超索引情况下 显示 IndexError 的全部内容, 来源链接: utcz.com/a/162381.html

回到顶部