Skip to content

Instantly share code, notes, and snippets.

@AndrewWCarson
Created July 11, 2021 09:32
Show Gist options
  • Save AndrewWCarson/16150020cf65acc0ab35686dec005746 to your computer and use it in GitHub Desktop.
Save AndrewWCarson/16150020cf65acc0ab35686dec005746 to your computer and use it in GitHub Desktop.
A simple python solution to the phone number word search problem here: https://www.youtube.com/watch?v=PIeiiceWe_w
#!/usr/bin/env python
import math
# Function: numberFromWord
# - wordString: a String representative of the word
# Returns:
# - number: an Integer representative of the screen based on map
def numberFromWord(wordStr):
phoneMap = {"a": 2, "b": 2, "c": 2,
"d": 3, "e": 3, "f": 3,
"g": 4, "h": 4, "i": 4,
"j": 5, "k": 5, "l": 5,
"m": 6, "n": 6, "o": 6,
"p": 7, "q": 7, "r": 7, "s": 7,
"t": 8, "u": 8, "v": 8,
"w": 9, "x": 9, "y": 9, "z": 9}
number = 0
for char in range(len(wordStr)):
number = number * 10
number += phoneMap[wordStr[char]]
return number
# Function: getWordsInPhoneNumber
# - phoneNumberString: a String representation of a phone number
# - wordStrings: an array of strings to search for in the number
# Returns:
# - found: an array of Strings found within the phone number
def getWordsInPhoneNumber(phoneNumberString, wordStrings):
found = []
wordNumbers = []
wordModulo = []
phoneNumber = int(phoneNumberString)
for index in range(len(wordStrings)):
# This line is very smart. The wordModulo variable will serve as a
# mask later when searching for the word.
wordModulo.append(10**len(wordStrings[index]))
wordNumbers.append(numberFromWord(wordStrings[index]))
# This while loop is where the fun happens, imo.
# Take the phone number as an integer, modulo it against wordModulo to
# leave a number the same size as the target word. Then, compare them.
# This way, the only comparison done is simple integer equals. Add the
# word if they're equal. After checking all the words this way, remove
# the last digit and repeat. Could easily pop the found words to reduce
# the number of searches when a word is found.
while phoneNumber != 0:
for index in range(len(wordNumbers)):
if phoneNumber % wordModulo[index] == wordNumbers[index]:
found.append(wordStrings[index])
phoneNumber = int(phoneNumber / 10)
return found
def test():
testWords = ["cab", "car", "yyz"]
print("Test words:")
for word in testWords:
print("%s: %d" % (word, numberFromWord(word)))
testPhoneNumber="122276789"
print("Test phone number: %s" % testPhoneNumber)
print(getWordsInPhoneNumber(testPhoneNumber, testWords))
if __name__ == "__main__":
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment