我的作业遇到以下问题:
Write a program that prints the longest substring of
s
in which the letters occur in alphabetical order. For example, ifs = azcbobobegghakl
, then your program should print:Longest substring in alphabetical order is: beggh
我为这个问题编写的代码是这样的:
s = 'azcbobobegghakl'
current_index = 1
first_index = 0
result_string = ''
current_string = s[first_index]
while current_index < len(s):
if ord(s[first_index]) <= ord(s[current_index]):
current_string += s[current_index]
elif ord(s[current_index]) < ord(s[first_index]):
current_string = ''
if len(current_string) > len(result_string):
result_string = current_string[:]
current_index += 1
first_index += 1
print('Longest substring in alphabetical order is: ' + result_string)
代码没有给出正确的结果,由于某种原因,它给出了 eggh
而不是 beggh
。
由于这是一项作业,我不要求您给我更正后的代码,而只是给我一个提示,说明我错在哪里,因为我想自己解决我的问题并且不想作弊。
谢谢。
最佳答案
错误在这里:
current_string = ''
当你发现 s[current_index]) < s[first_index]
时,你不应该清除它。 .
其他提示:
- 无需使用
ord
. - 如果
s='a'
会发生什么? - 无需复制
result_string = current_string[:]
,因为字符串是不可变的
提示结束;P
关于python - 为什么下面的Python代码是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951203/