我在学校修了一门Python 2.7课程,他们让我们创建以下程序:
Assume s is a string of lower case characters.
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
In the case of ties, print the first substring.
For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
我写了以下代码:
s = 'czqriqfsqteavw'
string = ''
tempIndex = 0
prev = ''
curr = ''
index = 0
while index < len(s):
curr = s[index]
if index != 0:
if curr < prev:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index]
tempIndex=index
elif index == len(s)-1:
if len(s[tempIndex:index]) > len(string):
string = s[tempIndex:index+1]
prev = curr
index += 1
print 'Longest substring in alphabetical order is: ' + string
老师还给了我们一系列的测试字符串来尝试:
^{pr2}$除最后一个问题外,所有这些问题都很好,最后一个问题的答案如下:
Longest substring in alphabetical order is: cz
但应该说:
Longest substring in alphabetical order is: avw
我把密码检查了一千遍,没有发现错误。你能帮帮我吗?在
这些线条:
彼此不同意。如果新的最佳字符串是
^{pr2}$s[tempIndex:index+1]
,那么您应该在If条件中比较的字符串的长度。将它们更改为彼此一致可以解决问题:我看到user5402已经很好地回答了您的问题,但是这个问题引起了我的兴趣,所以我决定重新编写您的代码。:)下面的程序使用与代码基本相同的逻辑,只是做了一些小的更改。在
在实际情况下避免使用索引,并直接在字符串(或其他容器对象)的内容上迭代,被认为更像python。这通常使代码更易于阅读,因为我们不必同时跟踪索引和内容。在
为了访问字符串中的当前和上一个字符,我们压缩输入字符串的两个副本,其中一个副本通过在开头插入空格字符来偏移。我们还将一个空格字符附加到另一个副本的末尾,这样当最长的有序子序列出现在输入字符串的末尾时,我们就不必进行特殊处理。在
输出
^{pr2}$指数是你的朋友。 下面是问题的简单代码。在
相关问题 更多 >
编程相关推荐