Python字符串部分习题
来源:互联网 发布:passport.js npm 编辑:程序博客网 时间:2024/06/02 06:13
8-10 回文是一个正向和逆向拼写都相同的单词,比如“noon” 和 “redivider”。递归的说,如果一个单词第一个和最后一个字母相同,并且中间是一个回文,则该单词是回文。 字符串切片可以接受第三个下标用来指定“步长”,即相邻的字符之间的距离。步长为2,意思是切片每次取接下来的第2个字符;步长3意思是每次取接下来第3个 字符,等等。 重要的是,步长为 -1 表示切片按照相反的方向访问字符串,所以切片[::-1]会得到一个逆序的字符串。 因此可以使用这个特性编写一个一行判断回文的 is_palindrome函数。
def is_palindrome(word): return word == word[::-1] tag = is_palindrome('noon') print tag tag1 = is_palindrome('redivider') print tag1 tag2 = is_palindrome('word') print tag2
8-12 ROT13是一个比较弱的加密形式,它涉及将单词中的每个字母“轮转”13个位置。轮转一个字母意思是在字母表中移动它,如果需要,从开头开始。所以‘A’移动3个位置是‘D’,而‘Z’移动一个位置是‘A’。
编写一个函数 rotate_word,接收一个字符串以及一个整数作为形参,并返回一个新字符串,其中的字母按照给定的整数值“轮转”位置。
1 import string 2 3 def rotate_letter(letter, n): 4 if letter.isupper(): 5 begin = ord('A') 6 elif letter.islower(): 7 begin = ord('a') 8 else: 9 return letter 10 11 index = ord(letter) - begin 12 result = (index + n) % 26 + begin 13 return chr(result) 14 15 16 def rotate_word(word, n): 17 res = '' 18 for letter in word: 19 res += rotate_letter(letter, n) 20 return res 21 22 23 if __name__ == '__main__': 24 print rotate_word('cheer', 7) 25 print rotate_word('melon', -10) 26 print rotate_word('sleep', 9)
0 0
- Python字符串部分习题
- Python文件部分习题
- Python自然语言处理第二章部分习题
- (Python)LeetCode 习题代码(部分)
- 习题8-5 使用函数实现字符串部分复制
- Python核心编程 第二版 第二章 部分习题解答
- python 核心练习第八章习题(部分)
- 字符串习题
- 字符串习题
- python 字符串错误+部分转码问题
- 笨方法学Python 习题 6: 字符串(string)和文本
- 笨方法学习Python-习题6:字符串(string)和文本
- 笨办法学python习题6 字符串和文本
- Python - 习题
- Python习题
- Python习题
- Python 习题
- 部分算法习题
- STL迭代器简介
- hdu 4960 Another OCD Patient(记忆化)
- 数据库结果集ResultSet详解
- AVL树的旋转,插入,删除操作
- HDU 4969 Just a Joke(积分)
- Python字符串部分习题
- 二叉树的遍历
- C++中构造函数能调用虚函数吗?
- 819抢枪
- 数据挖掘笔记-分类-贝叶斯-原理与简单实现
- gdb如何显示宏定义的值
- 一个经典编程面试题的“隐退”
- osgi实战学习之路:8. Service-3之ServiceTracker
- poj 2074Line of Sight