summaryrefslogtreecommitdiff
path: root/lib/thandy/util.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/thandy/util.py')
-rw-r--r--lib/thandy/util.py20
1 files changed, 20 insertions, 0 deletions
diff --git a/lib/thandy/util.py b/lib/thandy/util.py
index b7281ae..2db7df4 100644
--- a/lib/thandy/util.py
+++ b/lib/thandy/util.py
@@ -3,6 +3,7 @@
import os
import sys
import tempfile
+import random
try:
import json
@@ -20,6 +21,7 @@ def moveFile(fromLocation, toLocation):
os.unlink(toLocation)
except OSError:
pass
+
os.rename(fromLocation, toLocation)
@@ -75,3 +77,21 @@ def getKeylist(keys_fname, checkKeys=True):
keydb.addFromKeylist(obj['signed'], allowMasterKeys=False)
return keydb
+
+def randChooseWeighted(lst):
+ """Given a list of (weight,item) tuples, pick an item with
+ probability proportional to its weight.
+ """
+
+ totalweight = sum(w for w,i in lst)
+ position = random.uniform(0, totalweight)
+ soFar = 0
+
+ # We could use bisect here, but this is not going to be in the
+ # critical path. If it is, oops.
+ for w,i in lst:
+ soFar += w
+ if position < soFar:
+ return i
+
+ return lst[-1][1]