Last active
January 13, 2018 09:28
-
-
Save nlpjoe/51c12e660cf31c63871c1fe773e0705c to your computer and use it in GitHub Desktop.
[bisect]用bisect来管理已排序的序列#python
This file contains 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
## 2.8 用bisect来管理已排序的序列 | |
import bisect | |
import sys | |
Haystack = [1, 4, 5, 6, 8 ,12, 15, 20, 21, 23, 23, 26, 29, 30] # 干草垛 | |
Needles = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31] # 针 | |
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}' | |
def demo(bisect_fn): | |
for needle in reversed(Needles): | |
position = bisect_fn(Haystack, needle) | |
offset = position * ' |' | |
print(ROW_FMT.format(needle, position, offset)) | |
if __name__ == '__main__': | |
if sys.argv[-1] == 'left': | |
bisect_fn = bisect.bisect_left | |
else: | |
bisect_fn = bisect.bisect | |
print('DEMO:', bisect_fn.__name__) | |
print('haystack ->', ' '.join('%2d' % n for n in Haystack)) | |
demo(bisect_fn) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment