Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import random
- class WeightedChoice(object):
- def __init__(self, weights):
- """Pick items with weighted probabilities.
- weights
- a sequence of tuples of item and it's weight.
- """
- self._total_weight = 0.
- self._item_levels = []
- for item, weight in weights:
- self._total_weight += weight
- self._item_levels.append((self._total_weight, item))
- def pick(self):
- pick = self._total_weight * random()
- for level, item in self._item_levels:
- if level >= pick:
- return item
- import csv
- weighed_items = [(item,float(weight)) for item,weight in csv.reader(open('file.csv'))]
- picker = WeightedChoice(weighed_items)
- print(picker.pick())
- lst = [ ('Orange', 0.10), ('Apple', 0.05), ('Mango', 0.15), ('etc', 0.69) ]
- x = 0.0
- lst2 = []
- for fruit, chance in lst:
- tup = (x, fruit)
- lst2.append(tup)
- x += chance
- tup = (x, None)
- lst2.append(tup)
- import random
- def pick_one(lst2):
- if lst2[0][1] is None:
- raise ValueError, "no valid values to choose"
- while True:
- r = random.random()
- for x, fruit in reversed(lst2):
- if x <= r:
- if fruit is None:
- break # try again with a different random value
- else:
- return fruit
- pick_one(lst2)
- def choose(items,chances):
- import random
- p = chances[0]
- x = random.random()
- i = 0
- while x > p :
- i = i + 1
- p = p + chances[i]
- return items[i]
- lst = [ ('Orange', 0.10), ('Apple', 0.05), ('Mango', 0.15), ('etc', 0.69) ]
- x = 0.0
- lst2 = []
- for fruit, chance in lst:
- low = x
- high = x + chance
- tup = (low, high, fruit)
- lst2.append(tup)
- x += chance
- if x > 1.0:
- raise ValueError, "chances add up to more than 100%"
- low = x
- high = 1.0
- tup = (low, high, None)
- lst2.append(tup)
- import random
- def pick_one(lst2):
- if lst2[0][2] is None:
- raise ValueError, "no valid values to choose"
- while True:
- r = random.random()
- for low, high, fruit in lst2:
- if low <= r < high:
- if fruit is None:
- break # try again with a different random value
- else:
- return fruit
- pick_one(lst2)
- # test it 10,000 times
- d = {}
- for i in xrange(10000):
- x = pick_one(lst2)
- if x in d:
- d[x] += 1
- else:
- d[x] = 1
- import random
- d= {'orange': 0.10, 'mango': 0.15, 'apple': 0.05}
- weightedArray = []
- for k in d:
- weightedArray+=[k]*int(d[k]*100)
- random.choice(weightedArray)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement