Skip to content

Instantly share code, notes, and snippets.

@zed
Created July 12, 2012 19:54
Show Gist options
  • Select an option

  • Save zed/3100522 to your computer and use it in GitHub Desktop.

Select an option

Save zed/3100522 to your computer and use it in GitHub Desktop.
longest prefix match
import string
import datrie # pip install datrie
def longest_match_datrie(search, hosts):
trie = datrie.new(alphabet=string.printable)
for url in hosts:
trie[url.decode('ascii')] = 1
matches = trie.keys(search.decode('ascii'))
return max(matches, key=len) if matches else ''
print longest_match_datrie("ab", ["ab", "abc", "cab", "cba",
"cabd", "cdab", "acbd", "bcad"])
# -> abc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment