random playing soundfiles according to rating.
Michael Spencer
mahs at telcopartners.com
Thu Feb 9 01:15:10 EST 2006
kp87 at lycos.com wrote:
...
>
> But i am stuck on how to do a random chooser that works according to my
> idea of choosing according to rating system. It seems to me to be a bit
> different that just choosing a weighted choice like so:
>
...
>
> And i am not sure i want to have to go through what will be hundreds of
> sound files and scale their ratings by hand so that they all add up to
> 100%. I just want to have a long list that i can add too whenever i
> want, and assign it a grade/rating according to my whims!
>
Perhaps something like this:
from bisect import bisect_left
from random import randrange
def w_choice(range, weights):
"""Return a choice from range, given *cumulative* relative frequencies"""
total = weights[-1]
pick = randrange(1,total)
ix = bisect_left(weights, pick)
return range[ix]
def cum_sum(iterable, start = 0):
cum = []
for i in iterable:
start += i
cum.append(start)
return cum
Test it:
>>> files = {"File1": 20, "File2": 10, "File3":70}
>>> def test(files, N = 10000):
... names = files.keys()
... weights = cum_sum(files.values())
...
... plays = {}
... for i in range(N):
... track = w_choice(names, weights)
... plays[track] = plays.get(track, 0) + 1
... return plays
...
>>> test(files, N=10000)
{'File3': 7039, 'File2': 1049, 'File1': 1912}
>>> files["File4"] = 50
>>> test(files, N=150000)
{'File3': 70502, 'File2': 9988, 'File1': 20009, 'File4': 49501}
>>>
Michael
More information about the Python-list
mailing list