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:
parent
751b5327a9
commit
c0268ed31a
1 changed files with 2 additions and 2 deletions
|
@ -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]
|
||||
|
|
Loading…
Reference in a new issue