edX MITx: 6.00.1x Introduction to Computer Science and Programming Using Python 课程 Week 1: Python
Posted 爱学英语的程序媛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了edX MITx: 6.00.1x Introduction to Computer Science and Programming Using Python 课程 Week 1: Python 相关的知识,希望对你有一定的参考价值。
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
# Paste your code into this box
count = 1
result = s[0]
while s:
newcount = 1
newresult = ‘‘
i = 0
while i+1<len(s):
if ord(s[i]) <= ord(s[i+1]):
newcount+=1
newresult+=s[i+1]
else:
break
i+=1
if newcount>count:
count = newcount
result = s[0]+newresult
s = s[i+1:]
print(result)
注:因为只是课程前期,故未使用sort()函数或一些其他高级函数。
有几点需要注意的地方:
1)不可去掉 newcount, newresult 变量,因为要找s中的最长子串,故如果后面能找到要替换掉前面稍短的子串
2)ord(s[i]) <= ord(s[i+1]): %注意是小于等于号
3)s = s[i+1:] %注意i+1:后面不加空格
以上是关于edX MITx: 6.00.1x Introduction to Computer Science and Programming Using Python 课程 Week 1: Python 的主要内容,如果未能解决你的问题,请参考以下文章
python MITx 600.1x |第1周| Python基础知识| 2.程序的核心要素|练习5b
python MITx 600.1x |第1周| Python基础知识| 2.程序的核心要素|练习5c
python MITx 600.1x |第1周| Python基础知识| 2.程序的核心要素|练习5d
python MITx 600.1x |第1周| Python基础知识| 2.程序的核心要素|练习5e