How to implement biased random function?

2024/9/21 4:29:00

My question is about random.choice function. As we know, when we run random.choice(['apple','banana']), it will return either 'apple' or 'banana' with equal probabilities, what if I want to return biased result, for example, rerurn 'apple' with 0.9 probability and 'banana' with 0.1 probability? How to implement this?

Answer

Luckily, in Python 3, you can simply use

import random
random.choices(a, probability)
#random.choices(population, weights=None, *, cum_weights=None, k=1)
https://en.xdnf.cn/q/72092.html

Related Q&A

Finding minimum value for each level of a multi-index dataframe

I have a DataFrame that looks like this:data a b 1 1 0.12 0.23 0.3 2 1 0.52 0.63 0.7and I want to find the minimum value for each level of a ignoring the b level, so as an output Im l…

Count occurrences of a list of substrings in a pyspark df column

I want to count the occurrences of list of substrings and create a column based on a column in the pyspark df which contains a long string.Input: ID History1 USA|UK|IND|DEN|MAL|SWE|AUS2…

What are screen units in tkinter?

I was reading the response in the link below and ran into screen units but I couldnt find what exactly was referred to by screen units in Jim Denneys response. I know they are not pixels. How do I use …

Python SUMPRODUCT of elements in nested list

I have two nested lists: a = [[1,2,3],[2,4,2]] b = [[5,5,5],[1,1,1]]I want to multiply and SUMPRODUCT each group of elements to get c = [[30],[8]]Which result from = [[1*5+2*5+3*5],[2*1,4*1,2*1]] Ive t…

Modifying viridis colormap (replacing some colors)

Ive searched around and found things that came close to working but nothing exactly suiting what I need. Basically, I really like the viridis colormap as a starting point. However, I would like to repl…

gtk minimum size

Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a TreeView, but is it available for general widgets?

How do I convert a json file to a python class?

Consider this json file named h.json I want to convert this into a python dataclass. {"acc1":{"email":"[email protected]","password":"acc1","name&…

PyTorch how to compute second order Jacobian?

I have a neural network thats computing a vector quantity u. Id like to compute first and second-order jacobians with respect to the input x, a single element. Would anybody know how to do that in PyTo…

Tensorflow setup on RStudio/ R | CentOS

For the last 5 days, I am trying to make Keras/Tensorflow packages work in R. I am using RStudio for installation and have used conda, miniconda, virtualenv but it crashes each time in the end. Install…

Cant import soundfile

Im using Anaconda and Im trying to import soundfile/pysoundfile. I installed the package by running conda install -c conda-forge pysoundfile and I think it succeeded because when I run conda list it sh…