Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random element by given priority [duplicate]

Tags:

python

random

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.

like image 779
Qiao Avatar asked Jun 07 '26 16:06

Qiao


1 Answers

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)
like image 167
sloth Avatar answered Jun 09 '26 06:06

sloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!