Last active
September 30, 2015 08:37
-
-
Save non/1753093 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
import random | |
import sys | |
if __name__ == "__main__": | |
args = sys.argv[1:] | |
if args: | |
need = int(args[0]) | |
f = open(args[1], 'r') if len(args) > 1 else sys.stdin | |
else: | |
print "usage: %s NUM [FILE] - pluck NUM lines from FILE (default stdin)" % args[0] | |
sys.exit(0) | |
# generalized knuth's shuffle to choose some number of lines to display | |
kept = [] | |
i = 0 | |
for line in f: | |
if i < need: | |
kept.append(line) | |
else: | |
j = random.randint(0, i) | |
if j < need: | |
kept[j] = line | |
i += 1 | |
for line in kept: | |
sys.stdout.write(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment