👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:
def weightedChoice(choices):
"""Like random.choice, but each element can have a different chance of
being selected.
choices can be any iterable containing iterables with two items each.
Technically, they can have more than two items, the rest will just be
ignored. The first item is the thing being chosen, the second item is
its weight. The weights can be any numeric values, what matters is the
relative differences between them.
"""
space = {}
current = 0
for choice, weight in choices:
if weight > 0:
space[current] = choice
current += weight
rand = random.uniform(0, current)
for key in sorted(space.keys() + [current]):
if rand < key:
return choice
choice = space[key]
return None
This function seems overly complex to me, and ugly. I"m hoping everyone here can offer some suggestions on improving it or alternate ways of doing this. Efficiency isn"t as important to me as code cleanliness and readability.
👻 Read also: what is the best laptop for engineering students?
We hope this article has helped you to resolve the problem. Apart from A weighted version of random.choice, check other code Python module-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano A weighted version of random.choice
- Deutsch A weighted version of random.choice
- Français A weighted version of random.choice
- Español A weighted version of random.choice
- Türk A weighted version of random.choice
- Русский A weighted version of random.choice
- Português A weighted version of random.choice
- Polski A weighted version of random.choice
- Nederlandse A weighted version of random.choice
- 中文 A weighted version of random.choice
- 한국어 A weighted version of random.choice
- 日本語 A weighted version of random.choice
- हिन्दी A weighted version of random.choice
Warsaw | 2023-01-31
Thanks for explaining! I was stuck with A weighted version of random.choice for some hours, finally got it done 🤗. Checked yesterday, it works!
Milan | 2023-01-31
I was preparing for my coding interview, thanks for clarifying this - A weighted version of random.choice in Python is not the simplest one. I just hope that will not emerge anymore
Tallinn | 2023-01-31
Maybe there are another answers? What A weighted version of random.choice exactly means?. Checked yesterday, it works!