Last active
August 16, 2019 20:18
-
-
Save jroyalty/23c6fce5ceef29daca14675b6100c9f3 to your computer and use it in GitHub Desktop.
One-pass weighted random sample (without replacement). Based on *Weighted Random Sampling* (2005; Efraimidis, Spirakis) [https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf]. Longer treatment here: https://krlmlr.github.io/wrswoR/articles/internal/wrswoR.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
class Item(object): | |
def __init__(self, label, weight): | |
self.label = label | |
self.weight = weight | |
self.nonce = 0.0 | |
def __repr__(self): | |
return f"{self.label}/w={self.weight}/nn={self.nonce}" | |
def __str__(self): | |
return self.label | |
items = [ | |
Item("ff", 100), | |
Item("ll", 5), | |
Item("ak", 99), | |
Item("cf", 100), | |
] | |
for i in items: | |
u = random.random() | |
ex = 1.0 / float(i.weight) | |
i.nonce = math.pow(u, ex) | |
print("input : ", items) | |
items_out = sorted(items, key=lambda x: x.nonce, reverse=True) | |
print("output: ", items_out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment