2020-04
21
字典真牛
字典用好了以后666得不知道该如何形容。创造字典,搜索词典,快得就像眨眼间。列表需要考虑的长度问题,字典里一个in就高效快捷了。
这是一道扯淡的习题,因为条件没固定,参考答案可以怎么参考呢?
Exercise 5: Two words are “rotate pairs” if you can rotate one of them and get the other (see rotate_word in Exercise 5). Write a program that reads a wordlist and finds all the rotate pairs. Solution: http://thinkpython2.com/code/rotate_pairs.py.
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 33 34 35 36 37 38 39 40 | def rotate_word(something, n): # a-z: 97-122, A-Z: 65-90 newletter1 = '' for letter in something: if ord(letter) < ord('A') or ord('Z') < ord(letter) < ord('a') or ord('z') < ord(letter): newletter2 = newletter1 + letter else: if ord(letter) + n > ord('z'): newletter2 = newletter1 + chr(ord(letter) + n - 26) elif ord('a') > ord(letter) + n > ord('Z'): newletter2 = newletter1 + chr(ord(letter) + n - 26) else: newletter2 = newletter1 + chr(ord(letter) + n) newletter1 = newletter2 return newletter2 def set_dict(fin): d = {} for line in fin: word = line.strip().lower() d[word] = 0 return d fin = open('words.txt') count = 0 d = set_dict(fin) for word in d: for i in range(1, 14): # 8.13.5的习题没有说要移多少位,参考答案直接定义为1-14位,你猜我在想什么 if rotate_word(word, i) in d: print(word, i, rotate_word(word, i)) count += 1 print(count) # ...... # zax 1 aby # zax 4 deb # zebu 7 glib # zebu 10 jole # zee 1 aff # zee 9 inn # zips 12 lube # zoa 6 fug # zoa 12 lam # 1137 |
还没有评论