Skip to content

Instantly share code, notes, and snippets.

@danob-jana
Last active November 30, 2015 20:32
Show Gist options
  • Save danob-jana/b9521a6777491ceeaf97 to your computer and use it in GitHub Desktop.
Save danob-jana/b9521a6777491ceeaf97 to your computer and use it in GitHub Desktop.
def zipf(n):
# element n is weighted by 1/n
cumulative_weight = 0
cumulative_weights = []
for n in range(1, n + 1):
cumulative_weight += 1.0 / n
cumulative_weights.append(cumulative_weight)
total_weight = cumulative_weights[-1]
r = random.random() * total_weight
for i, w in enumerate(cumulative_weights):
if r < w:
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment