think python 第9章 case study:word play

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 True
    else:
        return False
    
print(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 += 1
    else:
        num += 1

print('%.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 False
        previous = c
    return True

或者是使用递归

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 += 1
    return True

9.7exercises

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

exercise9.7

fin = open('words.txt')

def is_answer(fin):
    for line in fin:
        i = 0
        while 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 line
            else:
                i += 1
        
print(is_answer(fin))

输出结果是:bookkeeper

官方给出的答案代码是:

def is_triple_double(word):
    """Tests if a word contains three consecutive double letters."""
    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


def 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 word


print '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 = 100000
    while 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) and
                is_huiwen(b) and
                is_huiwen(c) and
                is_huiwen(d))
        i += 1

print(is_answer())
#没有输出结果,不知道原因是什么?

官网答案:

def has_palindrome(i, start, len):
    s = str(i)[start:start+len]
    return s[::-1] == s
    

def check(i):
    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))


def check_all():
    i = 100000
    while i <= 999996:
        if check(i):
            print (i)
        i = i + 1


print ('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 = 0
    count = 0
    while True:
        mother = daughter + diff
        if are_reversed(daughter, mother) or are_reversed(daughter, mother+1):
            count = count + 1
            if flag:
                print (daughter, mother)
        if mother > 120:
            break
        daughter = daughter + 1
    return count
    

def check_diffs():
    diff = 10
    while diff < 70:
        n = num_instances(diff)
        if n > 0:
            print (diff, n)
        diff = diff + 1

print ('diff  #instances')
check_diffs()

print
print ('daughter  mother')
num_instances(18, True)

 

posted on 2017-11-27 20:17  土间埋  阅读(434)  评论(0编辑  收藏  举报

导航