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中使用logging模块打印log日志详解

学一门新技术或者新语言,我们都要首先学会如何去适应这们新技术,其中在适应过程中,我们必须得学习如何调试程序并打出相应的log信息来,正所谓“只要log打的好,没有bug解不了”,在我们熟...

python 通过xml获取测试节点和属性的实例

写在前面:通过xml获取测试数据,主要是为了使数据参数化。测试脚本和测试数据分离,使得脚本清晰容易维护,方便排查问题。 XML:可扩展的标记语言,是一种用于标记电子文件使其具有结构行的...

查看python安装路径及pip安装的包列表及路径

查看python安装路径及pip安装的包列表及路径

一、Linux系统 查看Python路径 whereis python 此命令将会列出系统所安装的所有版本的Python的路径效果如下:  使用以下命令可分别查看Pytho...

python调用matlab的m自定义函数方法

项目信号处理和提取部分用到了matlab,需要应用到工程中方便研究。用具有万能粘合剂之称的“Python”。具体方法如下: 1.python中安装mlab 下载https://pypi...

用pywin32实现windows模拟鼠标及键盘动作

因为要批量用某软件处理一批eps文件,所以要模拟鼠标及键盘动作,使其能够自动化操作。 复制代码 代码如下:#-*-coding:utf-8-*-import osimport timei...