Think Python Exercise 9.6

编写一个名为is_abecedarian 的函数, 如果单词中的字符以字符表的顺序出现 (允许重复字符),则返回True。有多少个具备这种特征的单词?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def word_abcde(word):
    alphabets = "abcdefghijklmnopqrstuvwxyz"
    i = 0
    front = 0 #前一个字母的序数
    mine = 0 #当前字母的序数
    while i < len(word):
        index = 0
        while index < len(alphabets):
            # print(i,word[i],index,alphabets[index])
            if word[i] == alphabets[index]:
                mine = index
                if mine < front:
                    return False
                else:
                    front = mine
                    break
            index += 1
        i += 1
    return True

def is_abecedarian(file_in):
    count = 0
    for line in file_in:
        word = line.strip()
        if word_abcde(word):
            count += 1
            #print(word)
    print(count)

fin = open('words.txt')

is_abecedarian(fin)

我所使用的这个单词表里,这样的单词有596个。