我正在嘗試編寫一個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