Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An intuitive method to sort results in a few lines (Python)
"""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.
import re
def split(string):
"""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)))
or -k.lower().find(query.lower()))
return sorted(results, key=key, reverse=True)
query = 'box'
items = ['box', 'candy box', 'boxy', 'Xbox', 'Dropbox', 'B-box', 'suboxide']
print(sort(query, items))
# Result
# ['box', 'candy box', 'B-box', 'boxy', 'Xbox', 'suboxide', 'Dropbox']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment