1. Peter Ward
  2. dotfiles

Commits

Peter Ward  committed 9e474c3

iterator version of sample

  • Participants
  • Parent commits 550c7a3
  • Branches flowblok

Comments (0)

Files changed (1)

File bin/sample

View file
  • Ignore whitespace
 #!/usr/bin/env python
 
-from random import random, sample
+from random import random, randint
 import sys
 
+def sample(seq, k):
+    them = []
+    for n, elem in enumerate(seq):
+        if len(them) < k:
+            them.append(elem)
+        else:
+            if randint(0, n) < k:
+                them[randint(0, k - 1)] = elem
+    return them
+
 arg = sys.argv[1]
 
 if '.' in arg:
 else:
     n = int(arg)
 
-    for line in sample(list(sys.stdin), n):
+    for line in sample(sys.stdin, n):
         sys.stdout.write(line)
         sys.stdout.flush()