Skip to content

Instantly share code, notes, and snippets.

@mohd-akram
Created January 3, 2013 17:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohd-akram/4445152 to your computer and use it in GitHub Desktop.
Save mohd-akram/4445152 to your computer and use it in GitHub Desktop.
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