Refactor random-choice

Prefer initializing `result` to an empty array of size `m`, which makes the
algorithm a bit more elegant.
This commit is contained in:
William Carroll 2020-11-17 23:54:54 +00:00
parent 751b5327a9
commit c0268ed31a

View file

@ -6,8 +6,8 @@ def choose_a(m, xs):
Randomly choose `m` elements from `xs`.
This algorithm runs in linear time with respect to the size of `xs`.
"""
result = xs[:m]
for i in range(m, len(xs)):
result = [None] * m
for i in range(len(xs)):
j = random.randint(0, i)
if j < m:
result[j] = xs[i]