Think Python Exercise 9.5

编写一个名为uses_all的函数,接受一个单词和一个必须使用的字符组成的字符串。如果该单词包括此字符串中的全部字符至少一次,则返回True。你能统计出多少单词包含了所有的元音字符aeiou吗?如果换成aeiouy 呢?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def uses_all(word, muststr):
    for i in muststr:
        count = 0 
        index = 0
        while index < len(word):
            if i == word[index]:
                break
            index += 1
        if index == len(word):
            return False
    return True

def count_word(file_in, als):
    count = 0
    for line in file_in:
        word = line.strip()
        if uses_all(word, als):
            count += 1
    print(count,"个单词包含了",als,"所有的字符")
    
fin = open('words.txt')

count_word(fin, "aeiouy")

运行结果:

598 个单词包含了 aeiou 所有的字符

42 个单词包含了 aeiouy 所有的字符

可以发现,uses_all函数和9.4的uses_only函数的实现一模一样,其实没必要再写一遍。