Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a random value exists from previous loop

I'm trying to generate a random value for each loop and save it to variable minimum WHILE doing a check if that number has already been generated before in one of the previous loops.

listQ basically contains 6 lines that were randomly chosen from a file. The lines were chosen from between 1 to max_line (which is basically 6 steps less than max_line value). So it's important that I have to generate a number that's a multiplier of 6.

for x in range(0, 10):
    minimum = random.randrange(0, max_line,6)
    maximum = minimum+6
    listQ = listQ[minimum:maximum]

A bit stuck here. A list maybe?

like image 647
user3431336 Avatar asked Feb 27 '26 08:02

user3431336


1 Answers

Keep a list of all the previous values and check each subsequent iteration.

# sets have faster "val in set?" checks than lists
# do this once, somewhere in your program
previous_vals = set()

# other stuff here, including main program loop
for x in range(0, 10):
    # find a unique, new random number while 
    # limiting number of tries to prevent infinite looping
    number_of_tries = 0
    MAX_TRIES = 10
    generating_random = true
    while generating_random:    
        minimum = random.randrange(0, max_line,6)
        if minimum not in previous_vals:
            previous_vals.add(minimum)
            generating_random = false
        number_of_tries += 1
        if number_of_tries == MAX_TRIES:
            raise RunTimeError("Maximum number of random tries reached!")

    maximum = minimum+6
    listQ = listQ[minimum:maximum]

Note that there are other functions for set than add if you want to modify your example.

I added a maximum number of tries too in order to prevent your code from getting stuck in an infinite loop, since I don't know anything about your input data to know what the likilhood of getting into this situation is.

like image 132
enderland Avatar answered Mar 01 '26 20:03

enderland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!