Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96171
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import bisect
15
16
17
def make_word_list():
18
"""Reads lines from a file and builds a list using append.
19
20
returns: list of strings
21
"""
22
word_list = []
23
fin = open('words.txt')
24
for line in fin:
25
word = line.strip()
26
word_list.append(word)
27
return word_list
28
29
30
def in_bisect(word_list, word):
31
"""Checks whether a word is in a list using bisection search.
32
33
Precondition: the words in the list are sorted
34
35
word_list: list of strings
36
word: string
37
38
returns: True if the word is in the list; False otherwise
39
"""
40
if len(word_list) == 0:
41
return False
42
43
i = len(word_list) // 2
44
if word_list[i] == word:
45
return True
46
47
if word_list[i] > word:
48
# search the first half
49
return in_bisect(word_list[:i], word)
50
else:
51
# search the second half
52
return in_bisect(word_list[i+1:], word)
53
54
55
def in_bisect_cheat(word_list, word):
56
"""Checks whether a word is in a list using bisection search.
57
58
Precondition: the words in the list are sorted
59
60
word_list: list of strings
61
word: string
62
"""
63
i = bisect.bisect_left(word_list, word)
64
if i == len(word_list):
65
return False
66
67
return word_list[i] == word
68
69
70
if __name__ == '__main__':
71
word_list = make_word_list()
72
73
for word in ['aa', 'alien', 'allen', 'zymurgy']:
74
print(word, 'in list', in_bisect(word_list, word))
75
76
for word in ['aa', 'alien', 'allen', 'zymurgy']:
77
print(word, 'in list', in_bisect_cheat(word_list, word))
78
79
80
81