random playing soundfiles according to rating.
Steve Holden
steve at holdenweb.com
Wed Feb 8 23:42:39 EST 2006
kp87 at lycos.com wrote:
> I am a little bit stuck ....
>
> I want to play a bunch of soundfiles randomly, but i want to give each
> soundfile a rating (say 0-100) and have the likelihood that the file be
> chosen be tied to its rating so that the higher the rating the more
> likely a file is to be chosen. Then i need some additional flags for
> repetition, and some other business. I am guessing a dictionary would
> be a great way to do this, with the key being the soundfile name and
> the values being my ratings and other flags & associated data.
>
> #soundfile name : [rating, %chance it will repeat/loop]
> sfiles = { ("sf001") : [85, 15],
> ("sf002") : [25, 75],
> ("sf003") : [95, 45],
> ("sf004") : [35, 95] }
>
>
> 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:
>
> def windex(lst):
> '''an attempt to make a random.choose() function that makes weighted
> choices
>
> accepts a list of tuples with the item and probability as a pair
> like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
> >>> y=windex(x)'''
> n = random.uniform(0, 1)
> for item, weight in lst:
> if n < weight:
> break
> n = n - weight
> return item
>
>
> 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!
>
A really cheesy scheme: decide you will allocate each file a probability
between 0 and 10 or 1 and 10 - whatever. 100 may be a bit much - do you
really need such fine discrimination?
If you have your list [(filename, prob), (filename, prob), ... ] then
construct a filename list as follows:
flist = []
for filename, prob in lst:
flist += [filename] * prob
Then choosing a filename becomes quite simple:
file_to_play = random.choice(flist)
The rest is up to you ...
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list