Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Weighted Stochastic algorithm in python and its Application in Lottery

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report