Get the App
SLTechnology News&Howtos  ›  Development  › 

Weighted Stochastic algorithm in python and its Application in Lottery

Shulou Source: shulou.com Published: 2022-06-03 06:11:44 10月03日 Update

What this article shares to you is about the weighted random algorithm in python and its application in the lottery. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Without saying much, let's take a look at it.

Weighted random heavy use in game development, a variety of lottery and explosive equipment, etc.

The operator configures the probability of the occurrence of each item as needed.

The idea of the weighted random algorithm we are going to talk about today is very simple, that is, "all items are formed into intervals according to their weights, and the heavy intervals are large." you can imagine it as a pie chart. then, throw the dice and see which interval it falls in. "

For example, Chestnut, there is a year-end lottery, the item is iphone/ipad/itouch.

The weight allocated by the organizer is [('iphone', 10), (' ipad', 40), ('itouch', 50)].

The idea can be explained with one line of code, that is, random.choice (['iphone'] * 10 + [' ipad'] * 40 + ['itouch'] * 50).

Next, we write a general function.

# coding=utf-8import randomdef weighted_random (items): total = sum (w for _, w in items) n = random.uniform (0, total) # throw dice for x on the pie chart W in items:# traverses to find out the interval if n [10p50100] cur = 0 for w in weights: cur = cur+w yield cur def _ call__ (self): return self.goods [bisect.bisect _ right (self.acc, random.uniform (0, self.total))] wr = WeightRandom ([('iphone', 10), (' ipad', 40), ('itouch')] 50)]) the above print wr () is the weighted random algorithm in python and its application in the lottery. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Intervals items algorithms dice bands applications code that is ideas more weights knowledge articles configuration practical careful important intuitive one line organizer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn Linux Shulou Tech Info Xiaomi