From c0268ed31a8049ce75a7e61737b8e520e7d5403e Mon Sep 17 00:00:00 2001 From: William Carroll Date: Tue, 17 Nov 2020 23:54:54 +0000 Subject: [PATCH] Refactor random-choice Prefer initializing `result` to an empty array of size `m`, which makes the algorithm a bit more elegant. --- scratch/facebook/hard/random-choice.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scratch/facebook/hard/random-choice.py b/scratch/facebook/hard/random-choice.py index 95029ceb8..95e834a2e 100644 --- a/scratch/facebook/hard/random-choice.py +++ b/scratch/facebook/hard/random-choice.py @@ -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]