Chapter 15

Task 1

Searching with built in functions

15.1: searching.py

find = "learning"
print("Enter the word to find: " + find)

words = ["We", "love", "learning", "to", "program"]

if find.lower() in map(str.lower, words):
  print("Word found at index:", words.index(find))
else:
  print("Word not found!")

Output

>>> Enter the word to find: learning
>>> Word found at index: 2

Task 2

Serial Search

15.2: serial.py

letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
         "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

find = "n"
print("Enter a letter to find: " + find)

if len(find) != 1:
  print("Please enter a single letter.")
  exit()

for x in letters:
  if x == find:
      index = letters.index(x)
      print("Letter found at index:", index)
      del letters[index]

      if x not in letters:
          print("Letter not found again")
          break

Output

>>> Enter a letter to find: n
>>> Letter found at index: 13
>>> Letter not found again

Task 3

Serial Search

15.3: binary.py

from words import getwords

words = getwords()

mindex = 0
maxdex = len(words) - 1

word: str = None

find = "p"
print("Enter a letter to find: " + find)

while word == None:
  index = int((mindex + maxdex) / 2)

  if words[index] == find:
      word = words[index]
      print("Letter found at index:", index)
      break

  if find in words[index:]:
      mindex = index
      continue

  if find in words[:index]:
      maxdex = index
      continue

  print("Letter not found")
  break

Output

>>> Enter a letter to find: p
>>> Letter not found

Also, because I felt like it, I wrote a binary search program that downloads the entire english dictionary and looks for a single word.

BTW, it is insanely fast, given it looks through nearly 171,476 words.

It finishes executing in just 1257649 ticks or 125.7649 milliseconds.

15.3: binary

from random import randint
from words import getwords

words = getwords()

mindex = 0
maxdex = len(words) - 1

word: str = None

find = words[randint(0, len(words) - 1)]
print('Finding', find)

while word == None:
  index = int((mindex + maxdex) / 2)

  if words[index] == find:
      word = words[index]
      print("Letter found at index:", index)
      break

  if find in words[index:]:
      mindex = index
      continue

  if find in words[:index]:
      maxdex = index
      continue

  print("Letter not found")
  break

Output

>>> Finding undecree
>>> Letter found at index: 427136