I\'m working through Allen Downey\'s How To Think Like A Computer Scientist, and I\'ve written what I believe to be a functionally correct solution to Exercise 10.1
An important thing is your index
function: It's the function that runs more than any function. When you don't need the index of the found word, why define a function to find that index?
if word1word2 in lst:
is enough instead of if index(lst, word1word2):
.
The same for if index(lst, word2word1):
.
OK. bisection works really faster than the in
syntax. To improve the speed a bit more, i suggest using the bisect_left
function directly in your interlockings
function.
For example instead of:
if index(lst, word1word2): # check to see if word1word2 is actually a word
total += 1
print "Word 1: %s, Word 2: %s, Interlock: %s" % (word1, word2, word1word2)
Use:
q = bisect_left(lst, word1word2)
if q != len(lst) and lst[q] == word1word2:
total += 1
print "Word 1: %s, Word 2: %s, Interlock: %s" % (word1, word2, word1word2)
A very slight improvement in speed.