python - 为什么下面的Python代码是错误的?

标签 python

我的作业遇到以下问题:

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 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] 时,你不应该清除它。 .

其他提示:

  1. 无需使用ord .
  2. 如果s='a'会发生什么?
  3. 无需复制result_string = current_string[:] ,因为字符串是不可变的

提示结束;P

关于python - 为什么下面的Python代码是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951203/

相关文章:

python - 无法让程序正确运行Python/Qt/PyQt

python - 为什么 sqlalchemy 的默认列值不起作用

python - Python中的平均计算

python - Web-ifing python 命令行脚本?

python - 如何获得 PyQt 方法的正确签名

python - 使用 Flask-Oauthlib 向 Facebook 进行身份验证时出现 "Invalid Response from Facebook"

python - 如何在需要 root 权限的 Ubuntu 上运行 Python 文件

Python 字典列表 : Get last item of each day

python - matplotlib:在函数中绘制图,然后将每个图添加到单个子图图中

python - 如何有效地对 Pytables 中的数据进行插值