国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現簡單查找最長子串功能示例

2020-02-16 01:22:46
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現簡單查找最長子串功能。分享給大家供大家參考,具體如下:

題目選自edX公開課 MITx: 6.00.1x Introduction to Computer Science and Programming 課程 Week2 的Problem Set 1的第三題。下面是原題內容。

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, ifs = '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
For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.

代碼如下:

# -*- coding:utf-8 -*-#! python2#判斷一個字符串內的字母是否是按字母表順序# 如IsStrIncre('abbcdg') 返回 True# IsStrIncre('abbadg') 返回 False# 如果只有一個字符,也返回Falsedef IsStrIncre(s):  for cnt in range(len(s) - 1):    if len(s) == 1:      return False    elif s[cnt] > s[cnt+1]:      return False  return Trues = 'abajsiesnwdw'# example codesubstr = ''for length in range(1, len(s)+1):  firstflag = True # a flag to remember the first string that satisfied the requirements           # and ignore the strings satisfied the requirements but appeared after  for cnt in range(len(s)-length+1):    if IsStrIncre(s[cnt: cnt+length]):      if firstflag:        substr = s[cnt: cnt+length]        firstflag = Falseprint 'Longest substring in alphabetical order is: ' + substr

運行結果:

Longest substring in alphabetical order is: ajs

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 彭山县| 连州市| 彰化县| 西平县| 南京市| 许昌市| 三台县| 万盛区| 江华| 榆林市| 湾仔区| 监利县| 黎城县| 墨玉县| 吴川市| 浦江县| 星座| 确山县| 大新县| 洛川县| 清河县| 乐安县| 衡东县| 克东县| 婺源县| 外汇| 汉阴县| 东平县| 务川| 蕉岭县| 青河县| 大邑县| 濉溪县| 庆城县| 梁平县| 大厂| 平利县| 怀化市| 兴安县| 辽阳市| 罗山县|