lundi 14 février 2022

how to distribute more ones using random function in python

I would like to make a list that contains value of '1's than other random number.

let's say I want 60% of '1's appear out of 10 elements. so 6 elements of 1s and 4 elements with random. here is how I approached.

import numpy as np
import random

# to avoid generating 1s..
list_60 = np.random.randint(2,11, 10) 

array([ 6,  2,  8,  6,  6,  3,  5, 10,  6,  8])


count = 0
percentage = int(len(list_60)*(0.6) + 0.5)
for i in range(0,len(list_60)):
    if count < percentage:
        list_60[i]=0
    count += 1

list_60
array([ 1,  1,  1,  1,  1,  1,  5, 10,  6,  8])


random.shuffle(list_60)
array([ 1,  1,  1,  6,  1,  5,  1,  1,  8, 10])

Precedure STEPS:

  1. create randint from 2 to 10.
  2. loop each element and based on the percentage. and change the element to 1s.
  3. shuffle the list for more variation.

I don't think this is smart way of generating more 1s. Is there fancy/smart way to create weighted randomness?

Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire