A simple implementation of Python with weighted random numbers

Source: Internet
Author: User

This method is commonly used with weighted random number generation method, the idea is to sum the weight value total, in 0 with the weight and total to obtain a random number rd, traverse the weight dictionary, accumulate its weight value weight_sum, when Rd is less than or equal to Weight_sum, Returns the current weight key value, as shown in the example code:

Import randomdef random_weight (Weight_data):     _total = sum (Weight_ Data.values ())     #  weight summation     _random = random.uniform (0,  _total)    #  in 0 with weights and before getting a random number      _curr_sum = 0     _ret = None    try:         _keys = weight_data.iterkeys ()     #  using iterkeys  in python2.x    except attributeerror:        _keys =  weight_data.keys ()         #  using keys   in python3.x   for _k in _keys:        _curr_sum +=  data[_k]             #  in Traversal, Accumulate current weight value         if _random <= _curr_sum:           #  returns the weight when the random number <= the current weight and key             _ret = _k            break     return _ret

The transfer value is a dictionary, key is the random data to get, key for its weight, such as {' A ': ten, ' B ': ' C ': 50}

A simple implementation of Python with weighted random numbers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.