Python An API takes in prefix of a username and returns all usernames which star
ID: 3728813 • Letter: P
Question
Python An API takes in prefix of a username and returns all usernames which start with prefix sorting lexicographically and truncated at 5 results. Use API call to dump username database by implementing the "extract" function, making calls to any types of "query". query function in main works as follows: query("a") #=> ["abracadara", "al", "alice", "alicia", "allen"] query("ab") #=> ["abracadara"] Assume all usernames are lowercase. def extract(query): # CODE HERE return [...] def main(): """Run solution""" # Sample implementation of the autocomplete API database = ["abracadara", "al", "alice", "alicia", "allen", "alter", "altercation", "bob", "element", "ello", "eve", "evening", "event", "eventually", "mallory"] query = lambda prefix: [d for d in database if d.startswith(prefix)][:5] assert extract(query) == database main()
Explanation / Answer
The required sample implementation of the AutoComplete API is as follows.
Python
def extract(query):
retlist = []
for word in database:
if word[0:len(query)] == query:
retlist.append(word)
if len(retlist) >= 5:
break
return retlist
def main():
"""Run solution"""
# Sample implementation of the autocomplete API
sorted(database) #sorting it would improve the complexity
print(extract("b"))
#database needs to be global to be accessible
database = ["abracadara", "al", "alice", "alicia", "allen", "alter", "altercation", "bob", "element", "ello", "eve", "evening", "event", "eventually", "mallory"]
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.