Skip to content

Commit ce8c3df

Browse files
authored
Refactor weighted_srs function for clarity and efficiency
1 parent 59ee92a commit ce8c3df

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

Week02/weighted_ebru_koksal.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import random
22

3-
def weighted_srs(data,n,weights,with_replacement=False):
4-
if with_replacement:return random.choices(data,weights=weights,k=n)
5-
pool=list(data);w=list(weights) if weights else None;res=[]
6-
for _ in range(n):
7-
i=random.choices(range(len(pool)),weights=w,k=1)[0] if w else random.randrange(len(pool))
8-
res.append(pool.pop(i))
9-
if w:w.pop(i)
10-
return res
3+
def weighted_srs(data, n, weights, with_replacement=False):
4+
5+
if weights: return random.choices(data, weights=weights, k=n)
6+
7+
if with_replacement:return random.choices(data,k=n)
8+
9+
return random.sample(data,k=n)

0 commit comments

Comments
 (0)