Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write code in order to generate random numbers in a way that a random number can only be printed once every 5 times

I’ve written code in python in order to generate random numbers between 110-115, 19 times. The code works however I would like to add code that states that the same random numbers cannot be printed out next to each other, they can only be printed out after the other 5 numbers have been used. for example:

[112, 113, 115, 110, 111, 114, 112, 113, 115, 110, 111, 114…]

until 19 values have been printed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have the following code:

import random

randomlist = []

for i in range(19):

n = random.randint(110,115)

randomlist.append(n)

print(*randomlist, sep = "\n")

>Solution :

Try this, to generate 19 nos where no repetition in 5 consecutive nos.

import random
randomlist = []
while len(randomlist) < 19:
    n = random.randint(110,115)
    if n not in randomlist[-5:]:
        randomlist.append(n)
    else:
        continue

Hope this helps…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading