zoukankan      html  css  js  c++  java
  • Byte of Python学习笔记(2)——回文练习

      Byte of Python 第111页有关回文的作业练习,原题为:要想检查文本是否属于回文需要忽略其中的标点、空格与大小写。例如,“Rise to vote, sir.”是一段回文文本,但是我们现有的程序不会这么认为。你可以改进上面的程序以使它能够识别这段回文吗?如果你需要一些提示,那么这里有一个想法 :使用一个元组 来保存所有需要禁用的字符,然后使用成员资格测试来确定一个字符是否应该被移除,即 forbidden = ( ! ,? , . , ...)——原书注

      问题的关键在于如何找出字符串中的特殊字符,可以采用提示中的办法,需要注意的一点是删除了一个元素之后,原来的数组会改变,因此要注意遍历过程中的序号的问题。

      我的代码如下:

    '''This is the readme of this project!
    
    Are you OK?'''
    
    forbindden_word = (' ',',','.','!','//','?')
    def ignore_word(text):     #去除忽略的特殊字符
        strdemo = list(text)
        count = 0
        for i in list(range((len(strdemo)))):
            if strdemo[i-count] in forbindden_word:
                del strdemo[i-count] #删除特殊字符
                count += 1
        result = ''.join(strdemo)
        return result
    def reverse(text):
            return text[::-1]
    def is_reverse(text):   #判断是否为回文
            return text == reverse(text)
    
    something = input('Please input some text:')
    if is_reverse(ignore_word(something)):
        print(ignore_word(something))
        print('Yes!This is a reverse sentense.')
    else :
        print(ignore_word(something))
        print('Oh!No!This is not a reverse sentense!')
  • 相关阅读:
    WCF 、Web API 、 WCF REST 和 Web Service 的区别
    BusyIndicator using MVVM 忙碌状态指示器的的实现
    复制文件夹的方法 .net
    SQL/LINQ/Lamda
    CSLA验证规则总结
    C++中GB2312字符串和UTF-8之间的转换
    如何用VC编写供PB调用的DLL
    【转】lucene4.3.0 配置与调试
    cygwin主要命令
    【转】eclipse中window->preference选项中没有tomcat的解决方法
  • 原文地址:https://www.cnblogs.com/fengf1/p/7811550.html
Copyright © 2011-2022 走看看