1

I am trying to write a code to generate random numbers of length l each consisting of a letter and its probability selection where the percentages sum to 100. For example : If I give Random(10,[("X",50),("Y",40),("Z",10)]) should give me "yxxzyyxzzx" i.e 10 random numbers in any fashion(it need not be of 50% of X and 40% of Y and 10% of Z,its just that the sum should be 100(50+40+10)). Similarly Random(5,[("X",50),("Y",40),("Z",10)]) should give me "XXYZZ"

I tried the following code :

from random import choice
def Random(length,weightedchoice):


   string=""
   for count in range(length):

         string+=weightedchoice([("X",50),("Y", 40), ("Z", 10)])
   return string
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Shraddha
  • 183
  • 1
  • 2
  • 10

1 Answers1

0

A naïve way of doing it (I'm actually not sure how this would work statistically) is to simply fill up a list of 100 elements of X, Y, and Z objects and then pick out a number of elements at random. Is this what you want? You can obviously see that this is not very space-efficient at all, mostly wondering if I'm getting at the general idea of what you're looking for (I'd prefer this to be in a comment but I can't post comments yet).

ejbs
  • 390
  • 1
  • 9