Search code examples
pythonrandom

how to randomize the number of rows in each generation?


I am making a code (game) where I need to randomize the number of rows (length) in a number array each time it's generated. What I mean is that when a new array is generated, I want the length of that array to be random, like in the first print to be 7, another print to be 4, etc.

This is my code:

import random 

def random_array():
    low = 0
    high = 200
    cols = 1
    lrows = 2
    hrows = 15

    x = [random.choices(range(low,high), k=cols) for _ in range(lrows,hrows)]
    
    print(', '.join(map(repr, x)))
    

random_array()

Now whenever I let the code run, it'll print an array only with the length of 13 (I think it subtracts the number of lrows (supposed to be the minimum amount of rows) with hrows (the maximum amount of rows))


Solution

  • you didn't randomize row number. for _ in range(lrows,hrows) will loop for 13 times because lrows=2 and hrows=15.

    To randomize row number, you can use for _ in range(random.randint(lrows,hrows)).

    random.randint(lrows,hrows) returns a random integer between lrows and hrows.