在此强调一点:
for i in range(1,5):
print(i)
answer:
1
2
3
4
for i in range(5):
print(i)
answer:
0
1
2
3
4
读取字符列表
在 for 循环中也可以使用文件对象。下面的这个程序读取整个 words.txt 文件,然后每行输出一个词:
fin = open('words.txt')
for line in fin:
word = line.strip()
print(word)
练习1:
写一个程序读取 words.txt,然后只输出超过20个字母长度的词(这个长度不包括转义字符)。
code:
fin=open('word.txt')
for line in fin:
word=line.strip()
if len(word)>20:
print(word+'\n')
练习2:
在1939年,作家厄尔尼斯特·文森特·莱特曾经写过一篇5万字的小说《葛士比》,里面没有一个字母e。因为在英语中 e 是用的次数最多的字母,所以这很不容易的。事实上,不使用最常见的字符,都很难想出一个简单的想法。一开始很慢,不过仔细一些,经过几个小时的训练之后,你就逐渐能做到了。
好了,我不扯淡了。 写一个名字叫做 has_no_e 的函数,如果给定词汇不含有 e 就返回真,否则为假。
修改一下上一节的程序代码,让它只打印单词表中没有 e 的词汇,并且统计一下这些词汇在总数中的百分比例。
code:
def has_no_e(word):
if not('e' in word):
return True
else:
return False
fin=open('word.txt')
i=0
j=0
for line in fin:
word=line.strip()
if has_no_e(word):
print(word)
i=i+1
j=j+1
print(i/j*100,'%')
练习3:
写一个名叫 avoids 的函数,接收一个单词和一个禁用字母组合的字符串,如果单词不含有该字符串中的任何字母,就返回真。 修改一下程序代码,提示用户输入一个禁用字母组合的字符串,然后输入不含有这些字母的单词数目。你能找到5个被禁用字母组合,排除单词数最少吗?
code:
for 1:
def avoid(no_word,word):
for letter in no_word:
if letter in word:
return False
return True
no_word=input('please input an avoiding string: ')
word=input('please input a word: ')
if avoid(no_word,word):
print('no-avoiding word!')
else:
print('has avoiding-word!')
for2:
def avoid(no_word,word):
for letter in no_word:
if letter in word:
return False
return True
def bubble_sort(blist,bword):
count = len(blist)
for i in range(0, count):
for j in range(i + 1, count):
if blist[i] > blist[j]:
blist[i], blist[j] = blist[j], blist[i]
bword[i],bword[j]=bword[j],bword[i]
return (bword[0],blist[0])
fin=open('word.txt')
#count = len(fin.readlines())
start=ord('a')
storage_word=[]
storage_num=[]
i=0
start=ord('a')
for a in range(1,ord('z')-3):
for b in range(a+1,ord('z')-2):
for c in range(b+1,ord('z')-1):
for d in range (c+1,ord('z')):
no_word=chr(start)+chr(start+a)+chr(start+b)+chr(start+c)+chr(start+d)
for line in fin:
word=line.strip()
if avoid(no_word,word):
i=i+1
storage_word.append(no_word)
storage_num.append(i)
i=0
start=start+1
print(bubble_sort(storage_num,storage_word))
print(storage_num)
print(storage_word,len(storage_word))
由于冒泡算法所需计算时间十分长,故没有尝试...(可能需要1个小时以上)
练习4:
写一个名叫uses_only的函数,接收一个单词和一个字母字符串,如果单词仅包含该字符串中的字母,就返回真。你能仅仅用 acefhlo 这几个字母造句子么?或者试试『Hoe alfalfa』?
code:
import re
from functools import wraps
def get_alpha_str4(s):
result = ''.join(re.split(r'[^A-Za-z]', s))
return result
def uses_only(word,s):
w=get_alpha_str4(word.lower())
for letter in w:
if not(letter in s):
return False
return True
if uses_only('Hoe alfalfa','acefhlo'):
print('True')
else:
print('False')
练习5:
写一个名字叫uses_all的函数,接收一个单词和一个必需字母组合的字符串,如果单词对必需字母组合中的字母至少都用了一次就返回真。有多少单词都用到了所有的元音字母 aeiou?aeiouy的呢?
code:
def uses_all(word,s):
for letter in s:
if not(letter in word):
return False
return True
fin=open('word.txt')
i=0
for line in fin:
word=line.strip()
if uses_all(word,'aeiou'):
i=i+1
print(i)
def uses_all(word, required):
return uses_only(required, word)
这就是一种新的程序开发规划模式,就是降低问题的复杂性和难度,还原到以前解决的问题,意思是你发现正在面对的问题是之前解决过的问题的一个实例,就可以用已经存在的方案来解决。
练习6:
写一个名字叫is_abecedarian的函数,如果单词中所有字母都是按照字母表顺序出现就返回真(重叠字母也是允许的)。有多少这样的单词?
code:
def is_abecedarian(word):
n=len(word)
for i in range(1,n):
last_one=ord(word[i-1])
next_one=ord(word[i])
if not(last_one==next_one or last_one==(next_one-1)):
return False
return True
fin=open('word.txt')
i=0
for line in fin:
word=line.strip()
if is_abecedarian(word):
i=i+1
print(i)
一种很好的替代思路就是使用递归:
def is_abecedarian(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
return is_abecedarian(word[1:])
另外一种方法是用 while 循环:
def is_abecedarian(word):
i = 0
while i < len(word)-1:
if word[i+1] < word[i]:
return False
i = i+1
return True
程序测试可以用来表明 bug 的存在,但永远不能表明 bug 不存在。
— Edsger W. Dijkstra
练习7:
给我一个有三个连续双字母的单词。我会给你一对基本符合的单词,但并不符合。例如, committee 这个单词,C O M M I T E。如果不是有单独的一个 i 在里面,就基本完美了,或者Mississippi 这个词:M I S I S I P I。如果把这些个 i 都去掉就好了。但有一个词正好是三个重叠字母,而且据我所知这个词可能是唯一一个这样的词。当然有有可能这种单词有五百多个呢,但我只能想到一个。是哪个词呢?写个程序来找一下这个词吧。
code:
def is_triple_double(word):
"""Tests if a word contains three consecutive double letters.
word: string
returns: bool
"""
i = 0
count = 0
while i < len(word)-1:
if word[i] == word[i+1]:
count = count + 1
if count == 3:
return True(这句加粗语句的位置不要搞错)
i = i + 2
else:
count = 0
i = i + 1
return False
fin=open('word.txt')
for line in fin:
word=line.strip()
if is_triple_double(word):
print(word)
练习8:
有一天我在高速路上开着车,碰巧看了眼里程表。和大多数里程表一样,是六位数字的,单位是英里。加入我的车跑过300,000英里了,看到的结果就是3-0-0-0-0-0.
我那天看到的很有趣,我看到后四位是回文的;就是说后四位正序和逆序读是一样的。例如5-4-4-5就是一个回文数,所以我的里程表可能读书就是3-1-5-4-4-5.
过了一英里之后,后五位数字是回文的了。举个例子,可能读书就是3-6-5-4-5-6。又过了一英里,六个数字中间的数字是回文数了。准备好更复杂的了么?又过了一英里,整个六位数都是回文的了!
那么问题俩了:我最开始看到的里程表的度数应该是多少?
写个 Python 程序来检测一下所有的六位数,然后输出一下满足这些要求的数字。
code:
from __future__ import print_function, division
def has_palindrome(i, start, length):
"""Checks if the string representation of i has a palindrome.
i: integer
start: where in the string to start
length: length of the palindrome to check for
"""
s = str(i)[start:start+length]
return s[::-1] == s
def check(i):
"""Checks if the integer (i) has the desired properties.
i: int
"""
return (has_palindrome(i, 2, 4) and
has_palindrome(i+1, 1, 5) and
has_palindrome(i+2, 1, 4) and
has_palindrome(i+3, 0, 6))(注意切片【2,6】则为2345)
def check_all():
"""Enumerate the six-digit numbers and print any winners.
"""
i = 100000
while i <= 999996:
if check(i):
print(i)
i = i + 1
print('The following are the possible odometer readings:')
check_all()
print()
练习9:
最近我看忘了妈妈,然后我们发现我的年龄反过来正好是她的年龄。例如,假如他是73岁,我就是37岁了。我们好奇这种情况发生多少次,但中间叉开了话题,没有想出来这个问题的答案。
我回家之后,我发现到目前位置我们的年龄互为逆序已经是六次了,我还发现如果我们幸运的话过几年又会有一次,如果我们特别幸运,就还会再有一次这样情况。换句话说,就是总共能有八次。那么问题来了:我现在多大了?
写一个 Python 程序,搜索一下这个谜语的解。提示一下:你可能发现字符串的 zfill 方法很有用哦。
mycode:
#Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
def str_fill(i,n):
return str(i).zfill(n)
def is_euqal(i,j):
return str_fill(i, 2) == str_fill(j, 2)[::-1]
def check():
flag1=0
mom=0
me=0
count=0
for i in range(100):
flag1=i
for j in range(100):
if is_euqal(flag1,j):
count=count+1
if count==6:
mom=flag1
me=j
flag1=flag1+1
if count==8:
print('mom=',mom,'me=',me)
mom=0
me=0
count=0
check()