2

I'm writing a ranking algorithm and I would like to add randomness factor .

I'm generating a list of 10 items where each item has a value from 1 to 10 :

l = [random.randint(1,10) for num in range(1, 11)]

I'm running this code around 400 times and storing the large list in a DB .

I would like to add probability to it, so 70% of the times it generate radom numbers between 1 and 5 for the first 5 items, and 5 to 10 for the last 5 items .

And 30% of the times it stays random without any probability (normal mode) .

How can I achieve this using python and it's random module ?

Edit : Some thinks that this might be a duplicate of this question, however it' not, because I'm not looking to choose items based on a probabiltiy, instead I would like to be distributed based on their weight .

Community
  • 1
  • 1
Anis Souames
  • 334
  • 1
  • 4
  • 13
  • @UrielEli I checked this before posting, I couldn't find out how it would help my case, because the user looks like he wants to to create a function to choose number from a list based on their probability, which is not exactly my case . – Anis Souames Jan 07 '17 at 20:34

1 Answers1

3

The following will generate the wanted random list:

import random


def next_random_list():
    # With 70% probability
    if random.randint(1, 10) <= 7:
        # Generate 5 random elements from 1 to 5
        a = [random.randint(1, 5) for _ in range(5)]

        # Generate 5 random elements from 5 to 10
        b = [random.randint(5, 10) for _ in range(5)]

        # Concatenate them
        return a + b
    else:
        # Return just a random list of 10 numbers from 1 to 10
        [random.randint(1, 10) for _ in range(10)]

and you can invoke it 400 times:

lists = [next_random_list() for i in range(400)]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • Thanks, Although that wasn't included in the original question , how can I make sure that I never get the same number in the list ? – Anis Souames Jan 07 '17 at 20:59
  • 1
    @AnisSouames Have a look at `random.sample`, e.g. `random.sample(range(5,10), 5)` for the second half. – tobias_k Jan 07 '17 at 21:01