我正在尝试编写一个Python程序,该程序将采用任何小写字母的字符串并返回其中最长的字母顺序字符串。以下是一段代码。While循环中的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 +移+ EXPAN] < = S [1 +移+ EXPAN]的行: 创建错误该字符串索引是该范围以外的。我发现加入expan会使索引超出范围,但不应该用最大的while循环解决这个问题吗?我感谢任何帮助。
这很可能是一次错误。因为len将比最后一个基于0的索引大1,所以while条件不应该是len(s)> 1 + shift + expan吗? –
@ 0101001101000010这不会解决它仍然会出界的错误。 's'有一个len长度为'3',但由于最大索引是'len(object)-1'和'shift + expan> 0',所以你只能索引到2。 – Pythonista
'S [0 +移+ EXPAN] <= S [1 +移+ EXPAN]'是对于b真和c,从而然后EXPAN是+ = 1,并且超出了范围,应添加像'的检查和扩大+ 1 + 1 + shift
depperm