"""This module sorts a list of results based on a query.
If there is an intersection between words in the query and a result, it
is placed near the beginning of the list (based on length of intersection).
If there is no intersection, the position of the query (substring) in the
result (string) is used for sorting. These results are placed toward the end
of the list.
"""Splits a string at special characters including whitespace"""
return [i for i in re.split(r'\W+', string.lower()) if i]
def sort(query, results):
"""Sort a list of results based on a query"""
querylist = split(query)
key = lambda k: (len(set(querylist).intersection(split(k)))
return sorted(results, key=key, reverse=True)
query = 'box'
items = ['box', 'candy box', 'boxy', 'Xbox', 'Dropbox', 'B-box', 'suboxide']
# ['box', 'candy box', 'B-box', 'boxy', 'Xbox', 'suboxide', 'Dropbox']