Created
November 5, 2011 10:10
-
-
Save matteobertozzi/1341360 to your computer and use it in GitHub Desktop.
Get 'n' higher values from 'items'
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
| #!/usr/bin/env python | |
| def bsearch(data, key, cmpfunc): | |
| end = len(data) | |
| start = 0 | |
| while start < end: | |
| m = (start + end) / 2 | |
| c = cmpfunc(data[m], key) | |
| if c == 0: | |
| return m | |
| if c < 0: | |
| start = m + 1 | |
| else: | |
| end = m | |
| return start | |
| def higher(n, items): | |
| """ | |
| Get 'n' higher values from 'items' | |
| """ | |
| hig = [] | |
| for i in items: | |
| h = bsearch(hig, i, lambda m, k: cmp(k, m)) | |
| if h < len(hig) and hig[h] == i: | |
| continue | |
| hig.insert(h, i) | |
| if len(hig) > n: | |
| hig.pop() | |
| return hig | |
| if __name__ == '__main__': | |
| print higher(4, [5, 8, 4, 3, 1, 14, 2, 6, 10, 12, 14]) | |
| print higher(2, ["Hello", "World", "Abby", "Th30z"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment