Skip to content

Instantly share code, notes, and snippets.

@ceciliaelena
Created December 15, 2020 12:31
Show Gist options
  • Save ceciliaelena/c7890249709e4bc64e8da19cdce045fa to your computer and use it in GitHub Desktop.
Save ceciliaelena/c7890249709e4bc64e8da19cdce045fa to your computer and use it in GitHub Desktop.
"""
Autocomplete exercise
"""
class AutoComplete:
"""This is the class that handles the autocomplete operation
This class will return a list of max 4 matches
:param: target: The input word we are searching
"""
dictionary = sorted([line.rstrip('\n').lower() for line in open('keywords.txt')])
def __init__(self, target):
self.target = self._is_valid_target(target)
def _is_valid_target(self, value):
target = str(value).lower()
if len(target.strip()) == 0 or not target.isalpha():
raise ValueError('Please enter a valid string')
return target
def get_matches(self):
matches = sorted([elem for elem in self.dictionary if self.target in elem])
if len(matches) > 4:
return matches[:4]
else:
return matches
def main():
word = input()
autocomplete = AutoComplete(target=word)
matches = autocomplete.get_matches()
print(f"Matches for {word}: are {matches}")
if __name__ == "__main__":
main()
Pandora
Pinterest
Paypal
Pg&e
Project
free
tv
Priceline
Press
democrat
Progressive
Project
runway
Proactive
Programming
Progeria
Progesterone
Progenex
Procurable
Processor
Proud
Print
Prank
Bowl
Owl
River
Phone
Kayak
Stamps
Reprobe
import os
import unittest
from autocomplete import AutoComplete
class TestAutoComplete(unittest.TestCase):
def test_word_autocomplete_1(self):
word = "pro"
expected = ['proactive','processor','procurable','progenex']
autocomplete = AutoComplete(target=word)
matches = autocomplete.get_matches()
self.assertEqual(matches,expected)
def test_word_autocomplete_2(self):
word = "p"
expected = ['pandora','paypal','pg&e','phone']
autocomplete = AutoComplete(target=word)
matches = autocomplete.get_matches()
self.assertEqual(matches,expected)
def test_word_autocomplete_not_in_list(self):
word = "ze"
expected = []
autocomplete = AutoComplete(target=word)
matches = autocomplete.get_matches()
self.assertEqual(matches,expected)
def test_raise_exception_empty_str(self):
word = ""
self.assertRaises(ValueError,AutoComplete,word)
def test_raise_exception_empty_not_alpha(self):
word = 12345
self.assertRaises(ValueError,AutoComplete,word)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment