edX MITx: 6.00.1x Introduction to Computer Science and Programming Using Python 課程 Week 1: Python Basics Problem Set 1 Problem 3

來源:互聯網
上載者:User

標籤:using   hat   asi   bcb   into   ast   bsp   box   science   

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 Basics Problem Set 1 Problem 3

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.