为什么以下Python代码错误?

时间:2014-02-22 07:23:37

标签: python

我的作业存在以下问题:

  

编写一个程序,打印s的最长子字符串,其中字母按字母顺序出现。例如,如果s = azcbobobegghakl,那么您的程序应该打印:

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。 由于这是一项任务,我不会要求你给我更正的代码,但只是给我一个关于我错在哪里的提示,因为我想通过MYSELF解决我的问题并且不想作弊。

感谢。

1 个答案:

答案 0 :(得分:1)

错误在这里:

current_string = ''

当你找到s[current_index]) < s[first_index]时,你不应该清除它。

其他提示:

  1. 无需使用ord
  2. 如果s='a'会怎样?
  3. 无需复制result_string = current_string[:],因为字符串是不可变的
  4. 提示OVER; P

相关问题