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.

Community
  • 1
  • 1
Qiao
  • 16,565
  • 29
  • 90
  • 117

1 Answers1

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)
sloth
  • 99,095
  • 21
  • 171
  • 219
  • I was going to suggest this until I realized there might be a better solution in the duplicate. – mgilson Sep 04 '12 at 14:49
  • thanks, so easy to get it. Finally I will start doing things now. Just need to mess a little with priorities and tasks ) – Qiao Sep 04 '12 at 14:58