2

Possible Duplicate:
Weighted random selection with and without replacement

I tired to make all decisions what to do next by myself. I want computer to do it. I only write things and give priority to each, computer selects one by these priorities with random element.

So, I made this file (tsv):

3   work A
2   work B
1   work C
1   laundry
1   nothing

"Work A" should happens with 38% probability. "nothing" - 13%, etc.
Computer should count all this and say to me: do ___

I can read it and get percents for each thing. But I cannot figure out how should I select one thing with these percents.

import csv

# reading
file = open('do.txt', mode='r', encoding='utf-8')
tsv_file = csv.reader(file, delimiter='\t')

# total priority
priority_total = 0
for work in tsv_file:
    priority_total = priority_total + int(work[0])

?????

print(do_this)

What is the way to do this? Is there a function for random selection with given probabilities?

I really need this to stop procrastinating and start doing things.

4

1 回答 1

3

Well, a simple approach would be to create a list of your tasks, but add each task a number of times to the list equal to its priority.

So after loading your file, the list would look like this:

['work A', 'work A', 'work A', 'work B', 'work B', 'work C', 'laundry', 'nothing']

and then you can use random.choice to select a random element.

task_list = []
for prio, work in tsv_file:
    task_list += [work] * int(prio)

do_this = random.choice(task_list)
于 2012-09-04T14:45:34.743 回答