9.1reading word lists

download words.txt以后,跟编码文件放置在同一文件夹之下。

书中的内容是:

>>>fin = open('words.txt')
>>>print(fin)
<open file 'words.txt',mode 'r' at 0xb7f4b380>
>>>fin.readline()
'aa\r\n'
>>>fin.readline()
'aah\r\n'

本机(python3.63):

>>>fin = open(words.txt)
>>>print (fin)
<_io.TextIOWrapper name='words.txt' mode='r' encoding='cp936'>
>>>fin.readline()
'aa\n'
>>>fin.readline()
'aah\n'

我们也可以使用strip剔除掉换行符

>>>line = fin.readline()
>>>word = line.strip()
>>>print (word)
aahed

打印文本的每一个单词

fin = open(words.txt)
for line in fin:word = line.strip()print(word)

9.2exercises

编写一个函数has_no_e,如果给定的单词不含‘e’,返回True

letter = input('please input:')
def has_no_e(letter):if 'e' in letter:return Trueelse:return Falseprint(has_no_e(letter))

修改上一部分,打印不含‘e’的单词,计算不含‘e’的百分比(截取以a开头的单词)

fin = open('words_1.txt')
count = 0
num = 0
for line in fin:if 'e' not in line:print (line)count += 1else:num += 1print('%.2f' % (count / (count + num)))

9.3search

9.4 looping with indices

对于is_abecedarian我们需要比较相邻的字幕,单纯使用for循环就很难达到效果。此时我们可以使用索引

def is_abecedarian(word):previous = word[0]for c in word:if c < previous:return Falseprevious = creturn True

或者是使用递归

def is_abecedarian(word):if len(word) <= 1:return Trueif word[0] > word[1]:return Falsereturn is_abecedarian(word[1:])

或则是使用while循环

def is_abecedarian(word):i = 0while i < len(word) - 1:if word[i+1] < word[i]:return Falsei += 1return True

9.7exercises

下面是3个课后练习题的答案

exercise9.7

fin = open('words.txt')def is_answer(fin):for line in fin:i = 0while len(line) >= 6 and len(line) - i >= 6:if line[i] == line[i+1] and line[i+2] == line[i+3] and line[i+4] == line[i+5]:return lineelse:i += 1print(is_answer(fin))

输出结果是:bookkeeper

官方给出的答案代码是:

def is_triple_double(word):"""Tests if a word contains three consecutive double letters."""i = 0count = 0while i < len(word)-1:if word[i] == word[i+1]:count = count + 1if count == 3:return Truei = i + 2else:count = 0i = i + 1return Falsedef find_triple_double():"""Reads a word list and prints words with triple double letters."""fin = open('words.txt')for line in fin:word = line.strip()if is_triple_double(word):print wordprint 'Here are all the words in the list that have'
print 'three consecutive double letters.'
find_triple_double()
print ''

exercise9.8

习题9.8比较有意思,大概意思是有一个6位数a,后四位是回文数字;a+1,后5位是回文数字;a+2,后4位是回文数字;a+3,6位数字都是回文数字。求a。

# exercise 9.8
'''首先定义一个回文判定函数'''
def is_huiwen(i):if i[::-1] == i:print (i)def is_answer():   i = 100000while i <= 999999:# for i in range(100000,999999):a = str(i)a = a[2:]b = str(i+1)b = b[1:]c = str(i+2)c = c[2:]d = str(i+3)return (is_huiwen(a) andis_huiwen(b) andis_huiwen(c) andis_huiwen(d))i += 1print(is_answer())
#没有输出结果,不知道原因是什么?

官网答案:

def has_palindrome(i, start, len):s = str(i)[start:start+len]return s[::-1] == sdef check(i):return (has_palindrome(i, 2, 4)   andhas_palindrome(i+1, 1, 5) andhas_palindrome(i+2, 1, 4) andhas_palindrome(i+3, 0, 6))def check_all():i = 100000while i <= 999996:if check(i):print (i)i = i + 1print ('The following are the possible odometer readings:')
print (check_all())

exercise9.9

这道题用到了zfill方法。

bytes.zfill(width) bytearray.zfill(width)Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-' is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq).
>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'

def str_fill(i, len):return str(i).zfill(len)def are_reversed(i, j):return str_fill(i,2) == str_fill(j,2)[::-1]def num_instances(diff, flag=False):daughter = 0count = 0while True:mother = daughter + diffif are_reversed(daughter, mother) or are_reversed(daughter, mother+1):count = count + 1if flag:print (daughter, mother)if mother > 120:breakdaughter = daughter + 1return countdef check_diffs():diff = 10while diff < 70:n = num_instances(diff)if n > 0:print (diff, n)diff = diff + 1print ('diff  #instances')
check_diffs()print
print ('daughter  mother')
num_instances(18, True)

转载于:https://www.cnblogs.com/Kingwjk/p/7892495.html

think python 第9章 case study:word play相关推荐

  1. Data Visualization – Banking Case Study Example (Part 1-6)

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  2. Python绝技第一章 入门 python3实现密码破解

    前言 对我而言,武术的非凡之处在于它的简单.简单的方法也是正确的方法,同时武术也没有什么特别之处.越接近武术的真谛,招式表现上浪费越少 简介 python 绝技 第一章是python入门语法,两个需要 ...

  3. 【IUI 2020】人在回路机器学习——Human-in-the-Loop AI in Government: A Case Study

    文章目录 摘要 1 引言 2 背景 3 设计与实施 3.1 收据扫描 3.2 图像处理 3.3 光学字符识别(OCR) 3.4 自然语言处理 3.5 机器学习分类 用户接口 总结 主要参考文献 摘要 ...

  4. 小牛叔讲Python第12章:面向对象类与实例(Class入门)

    上一篇:小牛叔讲Python第11章:函数的高级用法以及匿名函数 下一篇:小牛叔讲Python第13章:类Class中的各种变量类型 小牛叔用轻松有趣的故事,带你进入Python的编程世界. 1.类 ...

  5. Web Service Case Study: 认证考试申请服务

    本文是Web Service Case Study系列文章的第二篇.在这篇文章中,我将围绕一个认证考试申请系统展开设计和讨论,这个应用与本文的系统不同,主要是面向B2C模式的应用,着眼点在于如何将这个 ...

  6. 【翻译】Deep Learning-Based Video Coding: A Review and A Case Study

    [翻译]Deep Learning-Based Video Coding: A Review and A Case Study [下载] 论文发布地址:https://arxiv.org/abs/19 ...

  7. Case study:在数据库网页中设计数据排序工具

    一.目的 该笔记的目的是引导读者在已搭建的数据库网页的基础上,利用JS设计数据排序工具.其效果如图1所示."Order by"下拉列表框由一系列字段组成,如"Locati ...

  8. Case Study: 利用PHP获取关系型数据库中多张数据表的数据

    一.目标 该笔记的目的是引导读者借助WampServer平台和MySQL数据库,利用HTML/CSS/JS/PHP设计一个多数据表关联的网页.在上一个案例(Case Study: 利用JS实现数据库网 ...

  9. Case Study: 利用JS实现数据库网页的数据分页、数据选择、数据详细信息查看功能

    一.目标 该笔记的目的是引导读者借助WampServer平台和MySQL数据库,利用HTML/CSS/JS/PHP设计一个能够进行实现数据分页显示.数据选择.数据详细信息查看功能的数据库网页.该数据库 ...

最新文章

  1. 转载:mouseOver/mouseOut 与 rollOver/rollOut的区别
  2. 揭秘全球首次互联网8K直播背后的技术实现
  3. ubuntu 13.04下MYSQL 5.5环境搭建
  4. PAT甲级1101 Quick Sort:[C++题解]DP、快速排序划分个数、快排
  5. oracle executesqlcommand,Oracle Execute Command Sql Script in Win
  6. 实验三 静态路由、默认路由配置
  7. Spartacus image alt属性的绑定实现
  8. Vscode linux ubuntu deb 最新下载
  9. Spring boot 2.x + Thymeleaf 公共部分抽取
  10. 注册测绘师学习笔记7
  11. 一起来作画吧「GitHub 热点速览 v.22.14」
  12. LM2596S-ADJ DC-DC降压芯片使用
  13. 电机转矩、功率、转速之间的关系及计算公式
  14. 高斯过程回归(Gaussian process regression)原理详解及python代码实战
  15. 配置失败还原请勿关闭计算机,电脑开机屏幕上面显示,配置失败还原更改 请勿关闭计算机 开不了机 这个问题怎么办...
  16. HashMap之链表转红黑树(树化 )-treefyBin方法源码解读(所有涉及到的方法均有详细解读,欢迎指正)
  17. DRC的报错类型及其对应的规则
  18. pythonmacd指标编写_利用python编写macd、kdj、rsi、ma等指标 -
  19. 计算机网络——第四章 网络层:数据平面
  20. SQL Server:国信证券赢在数字化转型起跑线的利器

热门文章

  1. Windows安全描述符SECURITY_DESCRIPTOR阅读注释
  2. 从工具了解大数据之Kettle
  3. 解决vue google无状态播放音频文件
  4. 【踩坑日记 · 嵌入式 Linux】在香橙派 Zero 2 上编译安装 CH340 驱动(OrangePi Zero 2)
  5. Xamarin.Forms学习之路——黑猫时钟App
  6. 互联网二次造富:从技术公司到运营平台的蜕变
  7. 干货 | Trip.com Android 11 适配之旅
  8. 八月冲刺月紧张记录(目标400+
  9. excel2010免费下载与安装
  10. @TableField fill