While循环中的Python范围错误

时间:2017-06-08 19:11:10

标签: python while-loop index-error

我正在尝试编写一个python程序,它将接受任何字符串的小写字母并返回其中最长的字母子字符串。以下是代码的一部分。

s="abc"                                            #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) >= 1+shift+expan:                     #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        while s[0+shift+expan] <= s[1+shift+expan]:  #while alphabetical
            expan += 1                               #checks next letter
        anslist += s[0+shift:2+shift+expan]       #adds substring to ans
        expan = 0                                  #resets expansion

当我运行代码时,包含的行 而s [0 + shift + expand]&lt; = s [1 + shift + expand]: 创建一个错误,表明字符串索引超出了范围。我看到添加到expand会使索引超出范围,但不应该是最大的while循环解决这个问题吗?我感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

首先,为什么你的代码不起作用:

  • 你不能保护你的内循环免于逃避字符串的结尾
  • 当&#34;保存&#34;时,您的索引已关闭子串
  • +=anslist,这不是你如何在列表中添加字符串
  • 在处理子字符串后,你不会增加shift,所以当它清除expan时,它会在相同的索引处重新开始并永远循环

固定代码(内联注释说明更改):

s="abckdefghacbde"                                 #sample string
anslist=[]                                         #stores answers
shift=0                                            #shifts substring
expan=0                                            #expands substring
while len(s) > 1+shift+expan:                      #within bounds of s
    if s[0+shift+expan] > s[1+shift+expan]:        #if not alphabetical
        shift += 1                                 #moves substring over
    else:                                          #if alphabetical
        # Added guard for end of string
        while len(s) > 1 + shift + expan and       # While still valid
              s[0+shift+expan] <= s[1+shift+expan]:# While alphabetical
            expan += 1                             #checks next letter
        # Fixed string sublength and append instead of +=
        anslist.append(s[0+shift:1+shift+expan])   #adds substring to ans
        # Continue to next possible substring
        shift += expan                             # skip inner substrings
        expan = 0  
print anslist

结果:

['abck', 'defgh', 'ac', 'bde']

所以最后一步是找到一个长度最长的那个,我将留给你,因为这看起来像是家庭作业。

回答这个问题:

  

我看到添加到expand会使索引超出范围,但不应该是最大的while循环解决这个问题吗?

它可以防止您的起始子字符串索引关闭,但不会阻止您的扩展。你必须防止这两种可能性。

答案 1 :(得分:0)

看看这个。

>>> import re
>>> words = []
>>> word = r'[a]*[b]*[c]*[d]*[e]*[f]*[g]*[h]*[i]*[j]*[k]*[l]*[m]*[n]*[o]*[q]*[r]*[s]*[t]*[u]*[v]*[x]*[y]*[z]*' # regex that would match sub-strings. Just extend it up to z. 
>>> string = "bacde"
>>> for m in re.finditer(word, string):
...         words.append(m.group())
>>> print(words) # list of substrings
['b', 'acde']

然后你可以从字符串列表中提取最大的字符串

>>> print(max(words, key=len))
acde