0

Need to write a program using Randomizing logic(Python). It can be like a generic function which takes versions and probability as input and returns a version. Probability can be anything like 1/2,1/3,1/4,1/5 and versions should be equally distributed accordingly

Komal G
  • 9
  • 3

2 Answers2

1

Python has a built-in random library that has a choice function that can do exactly what you want.

import random
My_choice = random.choices(population, weights=None, cum_weights=None, k=1)

The value of the weights may be used to build a non-uniform probability density function. and cum_weights can be used to make a uniform probability with the sum of all weights.

You can read more about the random modules in their documentation.

OZahed
  • 464
  • 5
  • 11
0
from random import randint

def random_version_generator(no_of_version):
    """
    As we have only 4 versions of template currently limiting with the
    validation and returning version 1

    """
    if no_of_version > 4:
        return 1
    r =randint(0,100)
    propability_per_version = [100 // no_of_version + int(x < 100 % no_of_version)for x in range(no_of_version)]

    for idx, i in enumerate(range(len(propability_per_version))):
        if r <= propability_per_version[i]:
            return idx + 1
        elif r <= propability_per_version[i] + propability_per_version[i+1]:
            return idx + 2
        elif r <= propability_per_version[i] + propability_per_version[i+1] + propability_per_version[i+1]:
            return idx + 3
        else:
            return idx + 4

You can get more about randomizing logic here https://www.geeksforgeeks.org/write-a-function-to-generate-3-numbers-according-to-given-probabilities/

To Know Regarding enumerate click here https://www.geeksforgeeks.org/enumerate-in-python/

Komal G
  • 9
  • 3