python - how to generate n random integers of k digits -


is there way create n random integers of k digits.

for example.. 2000 random integers comprising of [0, 2, 3]

my trick use random number of generator , assign values based on the ranges?

but wondering if there better way in python?

edit: example: [0,0,0, 2, 2,3,0,0,2,2,..... 2000 elements] comprising of 0,2 , 3 approach

    def assign(x):         if x< 0.3: return 0         elif x<0.6: return 2         else: return 3      x = np.random.rand(num)      x = map(lamdba x:assign(x),x) 

from sounds of it, looks want generate sequence of length n using values found within list k.

python's random.choice function combined list comprehension perfect this.

the following function generate list of length n each element being random element chosen k.

from random import choice  def random_choices(n, k):     return [choice(k) _ in xrange(n)] 

here same thing simple list comprehension.

from random import choice foo = [choice(k) _ in xrange(n)] 

*thanks mr.goosberry pointing out xrange should replaced range in python 3.x.x.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -