'How do I make an uneven probability to choose one of so many functions?
I'm writing an "AI" (more like a chatbot), and I have a bunch of different functions it can do. It can send a wikipedia article, post a meme, ask a question, etc. I want each of these possible outcomes to have a different weighted probability (IE, 30% chance of it posting a meme, only 10% for it posting a meme, etc) the obvious way to do this is to get a random float and just check if the value is less than a given one. The problem with this is I' m going to be adding more functions and I want to tweak the probability of each outcome as I go so it feels better. What is the best way to choose between these functions in an easily-choosable way?
Solution 1:[1]
maybe make a dictionary where its entries have a function and a weight, so if you add another function later on, you just have to give it a weight compared to others (for example a function of weight 2 has double chance of appearing than a function of weight 1)
functions = {'joke':[joke_fn,its_weight],....}
then when making a decision, either figure out the maths of the random number you need to generate, or just roll a random number for every function and multiply it by the weight and pick the function with the highest roll*weight.
Edit: also np.random.choices([x[0] for x in functions],[x[1] for x in functions]) will work.
Solution 2:[2]
Using random.choices as suggested in the comments, I would do something like this:
import random
def did_you_know(a,b,op):
print(f"Did you know that {a} {op} {b} = {eval(f'{a}{op}{b}')}?")
def add(a,b): return(did_you_know(a,b,"+"))
def subtract(a,b): return(did_you_know(a,b, "-"))
def multiply(a,b): return(did_you_know(a,b,"*"))
def divide(a,b): return(did_you_know(a,b,"/"))
functions = [[add, 1],
[subtract, 2],
[multiply, 2]]
for x in random.choices(*list(zip(*functions)), k = 5):
x(5,3)
print('--- Add divide to the list of functions ---')
functions.append([divide, 3])
for x in random.choices(*list(zip(*functions)), k = 5):
x(7, 2)
Did you know that 5 * 3 = 15?
Did you know that 5 * 3 = 15?
Did you know that 5 - 3 = 2?
Did you know that 5 + 3 = 8?
Did you know that 5 * 3 = 15?
--- Add divide to the list of functions ---
Did you know that 7 / 2 = 3.5?
Did you know that 7 * 2 = 14?
Did you know that 7 * 2 = 14?
Did you know that 7 - 2 = 5?
Did you know that 7 * 2 = 14?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
