Python实现简单查找最长子串功能示例

yipeiwu_com5年前Python基础

本文实例讲述了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
# 如果只有一个字符,也返回False
def IsStrIncre(s):
  for cnt in range(len(s) - 1):
    if len(s) == 1:
      return False
    elif s[cnt] > s[cnt+1]:
      return False
  return True
s = 'abajsiesnwdw'# example code
substr = ''
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 = False
print 'Longest substring in alphabetical order is: ' + substr

运行结果:

Longest substring in alphabetical order is: ajs

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python实现apahce网站日志分析示例

维护脚本一例,写得有点乱,只是作为一个实例,演示如何快速利用工具快速达到目的:应用到:shell与python数据交互、数据抓取,编码转换 复制代码 代码如下:#coding:utf-8...

关于Python中浮点数精度处理的技巧总结

关于Python中浮点数精度处理的技巧总结

前言 最近在使用Python的时候遇到浮点数运算,发现经常会碰到如下情况: 出现上面的情况,主要还是因浮点数在计算机中实际是以二进制保存的,有些数不精确。 比如说: 0.1是十进制,...

深入Python函数编程的一些特性

绑定 细心的读者可能记得我在 第 1 部分的函数技术中指出的限制。特别在 Python 中不能避免表示函数表达式的名称的重新绑定。在 FP 中,名称通常被理解为较长表达式的缩写,但这一说...

python实现屏保程序(适用于背单词)

python实现屏保程序(适用于背单词)

今天要给大家分享的是一款自己写的屏保程序,大学大家最头疼的就是四六级的考试了,上次考试做阅读的时候,情不自禁的发呆,想着如果我能在电脑上写一个屏保程序,那么就可以天天记单词了! 开始 首...

在python 不同时区之间的差值与转换方法

之前有个程序,里面有个时间部分是按照国内时区,也就是东八区,来写的,程序中定义了北京时间2点到八点进行检查;后面程序在国外机器上,例如说韩国,欧美等,执行的时候发现会有时间上的问题,因为...