3

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.

2
  • I like this answer. Commented Sep 4, 2012 at 14:48
  • didn't know that is "weighted" Commented Sep 4, 2012 at 14:58

1 Answer 1

4

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

I was going to suggest this until I realized there might be a better solution in the duplicate.
thanks, so easy to get it. Finally I will start doing things now. Just need to mess a little with priorities and tasks )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.