首先,为什么你的代码不起作用:你没有保护你的内部循环不让它跑出来
“保存”子字符串时,索引将关闭
您+=到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
结果:
^{pr2}$
所以最后一步是找出最长的那个,我留给你们,因为这看起来像是家庭作业。在
要回答这个问题:I see that adding to expan will put the index out of range, but shouldn't the largest while loop solve this?
它可以防止起始子字符串索引停止运行,但不能防止扩展。你必须防范这两种可能性。在