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

Random number generator generating more than specified numbers

I’m working on an exercise: create a function which retuns a list with "n" non-duplicated random numbers, in crescent order, from 1-60.

The code is working fine, but eventually it generates more than "n" numbers (about 1/7 times).

Heres the code:

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

import random

def r_list (n):
  r_list = []
  while len(r_list) < n:
    for i in range(n):
      rn = random.randint(1,61)
      if rn not in r_list:
         r_list.append(rn)
      else:
        continue
  r_list.sort()
  
  print(r_list)

Why it generates more than "n" numbers? How do I fix this?

>Solution :

your inner loop is the problem, as long as you are using that it’ll add extras.

import random

def r_list (n):
  r_list = []
  while len(r_list) < n:
    rn = random.randint(1,61)
    if rn not in r_list:
      r_list.append(rn)
    else:
      continue
   r_list.sort()
  
  print(r_list)
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