📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division1213import bisect141516def make_word_list():17"""Reads lines from a file and builds a list using append.1819returns: list of strings20"""21word_list = []22fin = open('words.txt')23for line in fin:24word = line.strip()25word_list.append(word)26return word_list272829def in_bisect(word_list, word):30"""Checks whether a word is in a list using bisection search.3132Precondition: the words in the list are sorted3334word_list: list of strings35word: string3637returns: True if the word is in the list; False otherwise38"""39if len(word_list) == 0:40return False4142i = len(word_list) // 243if word_list[i] == word:44return True4546if word_list[i] > word:47# search the first half48return in_bisect(word_list[:i], word)49else:50# search the second half51return in_bisect(word_list[i+1:], word)525354def in_bisect_cheat(word_list, word):55"""Checks whether a word is in a list using bisection search.5657Precondition: the words in the list are sorted5859word_list: list of strings60word: string61"""62i = bisect.bisect_left(word_list, word)63if i == len(word_list):64return False6566return word_list[i] == word676869if __name__ == '__main__':70word_list = make_word_list()7172for word in ['aa', 'alien', 'allen', 'zymurgy']:73print(word, 'in list', in_bisect(word_list, word))7475for word in ['aa', 'alien', 'allen', 'zymurgy']:76print(word, 'in list', in_bisect_cheat(word_list, word))7778798081