1111
1212from __future__ import print_function , division
1313
14- from bisect import bisect_left
14+ import bisect
1515
1616
1717def make_word_list ():
@@ -35,17 +35,43 @@ def in_bisect(word_list, word):
3535 word_list: list of strings
3636 word: string
3737 """
38- i = bisect_left (word_list , word )
39- if i != len (word_list ) and word_list [i ] == word :
38+ if len (word_list ) == 0 :
39+ return False
40+
41+ i = len (word_list ) // 2
42+ if word_list [i ] == word :
4043 return True
44+
45+ if word_list [i ] > word :
46+ # search the first half
47+ return in_bisect (word_list [:i ], word )
4148 else :
49+ # search the second half
50+ return in_bisect (word_list [i + 1 :], word )
51+
52+
53+ def in_bisect_cheat (word_list , word ):
54+ """Checks whether a word is in a list using bisection search.
55+
56+ Precondition: the words in the list are sorted
57+
58+ word_list: list of strings
59+ word: string
60+ """
61+ i = bisect .bisect_left (word_list , word )
62+ if i == len (word_list ):
4263 return False
4364
65+ return word_list [i ] == word
66+
4467
4568if __name__ == '__main__' :
4669 word_list = make_word_list ()
4770
48- for word in ['alien' , 'allen' ]:
71+ for word in ['aa' , ' alien' , 'allen' , 'zymurgy ' ]:
4972 print (word , 'in list' , in_bisect (word_list , word ))
5073
74+ for word in ['aa' , 'alien' , 'allen' , 'zymurgy' ]:
75+ print (word , 'in list' , in_bisect_cheat (word_list , word ))
76+
5177
0 commit comments