While循环中的Python范围错误
我正在尝试编写一个python程序,它将接受任何小写字母字符串并返回其中最长的字母顺序子字符串。下面是一段代码While循环中的Python范围错误,python,while-loop,index-error,Python,While Loop,Index Error,我正在尝试编写一个python程序,它将接受任何小写字母字符串并返回其中最长的字母顺序子字符串。下面是一段代码 s="abc" #sample string anslist=[] #stores answers shift=0 #shifts su
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=“abc”#示例字符串
anslist=[]存储答案
移位=0#移位子串
expan=0#展开子字符串
而len(s)>=1+shift+expan:#在s的范围内
如果s[0+shift+expan]>s[1+shift+expan]:#如果不是按字母顺序排列
shift+=1#将子字符串移到
其他:#如果按字母顺序排列
而s[0+shift+expan]来看看这个
>>> 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
首先,您的代码不起作用的原因:
- 您没有保护您的内部循环,以防从字符串末尾跑掉
- “保存”子字符串时,索引处于关闭状态
- 您将
+=
添加到anslist
上,这不是向列表添加字符串的方式
- 在处理子字符串之后,不会增加移位,因此当它清除expan时,它将在相同的索引处重新开始并永远循环
固定代码(内联注释解释更改):
所以最后一步是找到长度最长的,我留给你,因为这看起来像是家庭作业
要回答这个问题:
我看到添加到expan会使索引超出范围,但是最大的while循环不应该解决这个问题吗
它可以防止起始子字符串索引关闭,但不能防止扩展。您必须防范这两种可能性。这很可能是一个一次性错误。while条件不应该是len(s)>1+shift+expan
,因为len将比最后一个基于0的索引大1吗?@0101001101000010不会修复错误,它仍然超出范围s
的len为3
,但你只能将其索引到2,因为最大索引为len(object)-1
和shift+expan>0
s[0+shift+expan]@Djokester帖子的第一句话不清楚吗?对我来说似乎很好…我更感兴趣的是了解是什么导致了上述代码中的错误,而不是创建另一个可以工作的程序。我仍然不太明白如何修复while循环问题。我认为他想要字母顺序,比如“abc”
或“def”
,而不仅仅是字母字符。参见他所说的字母子字符串。我评论说,他想要什么还不清楚。他应该给出一个预期的产出,只要abc没有达到这个目标@乔克斯特:很抱歉给你添麻烦。对于s=“abc”,预期输出为“abc”。类似地,对于s=“bac”,预期输出为“ac”。@GradyMorrissey已被编辑以匹配您的查询。只要将regex模式扩展到zI就行了。我们已经在这段代码上工作了两天,终于找到了错误所在,这太棒了。非常感谢您的详细回复,也感谢所有对此问题做出贡献的人的帮助@GradyMorrissey在将来,请包括堆栈跟踪,因为这样可以更容易地确定具体问题。另外,我建议大家看一看,因为有一些重要的风格问题使代码难以阅读。话虽如此,不要气馁。每个人都会犯错。
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']