Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

An intuitive method to sort results in a few lines (Python)

View query_sort.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
"""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
Something went wrong with that request. Please try again.