Created
July 12, 2012 19:54
-
-
Save zed/3100522 to your computer and use it in GitHub Desktop.
longest prefix match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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