Wretch11 Wretch11 - 1 month ago 8
Python Question

Populate two arrays of random length, with random numbers, using a list comprehension

As the title suggests, i want to populate two separate lists, each with it's own random length and content using a list comprehension, something along the lines of:

a, b = [random.randint(1,100), random.randint(1,100) for x in range(random.randrange(1,10))]


Can it be done in a single line? If so how would i go about it?

Thanks

Answer Source

Firstly, you want to repeat the same function twice instead of creating two arrays separately. So let's write a function random_array

Now, we can use random.choice(range(int)) to select a random number, e.g.

>>> choice(range(10))
7

Alternatively, we can use random.randint(0, 10) too:

>>> random.randint(0, 10)
5

Then, we can randomly choose N no. of integers given a range using random.sample:

>>> n = 5
>>> random.sample(range(10), n)
[3, 2, 1, 9, 4]

So using random.sample and random.choice:

>>> from random import sample, choice
>>> def random_array(maxsize, maxint):
...     return sample(range(maxint), choice(range(maxsize)))
... 
>>> random_array(10, 100)
[12, 9, 62, 48, 11, 44, 58, 52, 1]
>>> random_array(10, 100)
[97, 78, 33, 3]

Or random.randint and random.sample:

>>> from random import randint, sample
>>> def random_array(maxsize, maxint):
...     return sample(range(maxint), randint(0, maxsize))
... 
>>> random_array(10, 100)
[27, 50, 95, 18, 4, 30, 73, 47]

Or using numpy:

>>> import numpy as np
>>> np.random.rand() # Random float between 0.0 to 1.0
0.7796560918112618
>>> np.random.rand(2)
array([ 0.75680381,  0.20146147])
>>> np.random.rand(2) # Random array of size 1x2 (column X row)
array([ 0.81612505,  0.42277987])

>>> np.random.rand(random.randint(0, maxsize)) # Random size array of len < maxsize
array([ 0.83846215,  0.77637599,  0.85086381,  0.03674837])
>>> np.random.rand(random.randint(0, maxsize)) # Random size array of len < maxsize
array([ 0.26468399,  0.0472708 ,  0.83615985,  0.20740113,  0.40436625,
        0.84332336,  0.48814732,  0.39267764,  0.30662132])
>>> np.random.rand(random.randint(0, maxsize)) * 100 # Random size array of len < maxsize and max value < 100
array([ 80.85771169,  50.49196633,  21.01646636,  36.15074652,
        97.98209728,  85.68512275,  58.06013557,  23.93219465,
         5.18467685,  12.77761391])

If you want a single liner:

a =  sample(range(100), choice(range(10)))