mardi 23 février 2021

Generate a list of 100 elements, with each element having a 50% chance of being 0, and a 50% chance of being a random number between 0 and 1

I am quite new in this and I am trying to learn on my own. As I said in the title, I am trying to create a list of 100 numbers whose elements are either 50% chance of being 0's or 50% change being a number between 0 and 1. I made it like the one below. It works but it is a very tedious and not well coded program. Any hints of how to make to make it better?

import random
import numpy as np

#define a list of 100 random numbers between 0 and 1
randomlist = []
for i in range(0,100):
    n = random.uniform(0,1)
    randomlist.append(n)
print(randomlist)


#create a list of 100 numbers of 0's and 1's
def random_binary_string(length):
    
    sample_values = '01' # pool of strings
    result_str = ''.join((random.choice(sample_values) for i in range(length)))
    return (result_str)

l=100
x=random_binary_string(l)
x1=np.array(list(map(int, x)))
print(x1)


#combine both lists. Keep value if of the binary list if it is equal to zero. Else, substitute it by the value of randomlist
#corresponding to the index position
finalist=[]
for i in range(len(x1)):
    if x1[i]==0:
        finalist.append(x1[i])
    else:
        finalist.append(randomlist[i])
        
print(finalist)    

Thanks a lot!




Aucun commentaire:

Enregistrer un commentaire