Random number generator generating more than specified numbers

Question:

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:

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?

Asked By: GLASS

||

Answers:

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)
Answered By: Mike Tung

Some considerations:

  1. the for loop is unnecessary (and also the cause of your problem) i’ll suggest just use a while loop
  2. The else:continue is redundant, i’ll suggest to get rid of that too
  3. return the list for some use case later.
  4. try first to clean your code to search the issue.

What is the Problem?

The problem is in the for loop, if the number is large enough it’ll append also when the list’s lenght is bigger than the original number.

For instance, in your for loop you asked it to do that loop first and then check for the lenght, this would result in adding more numbers and not checking if the numbers are overflowing.

How can i fix it?

Well, the problem can be fixed in many ways but i will suggest to remove the for loop as in point 1. of the considerations pointed before

This is a demostration of the implementation using the considerations above:

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)
...     return r_list

here is another way of how you could accomplish this without taking out the for loop:

import random

def r_list (n):
  r_list = []
  while len(r_list) < n:
    for x in range(n):
      rn = random.randint(1,61)
      # don't add more numbers when condition is met
      if len(r_list) > n:break 
      if rn not in r_list:
        r_list.append(rn)
   r_list.sort()
  
  print(r_list)

How can I prevent from happening again?

Well, the simplest way is to not append the things to the list before the check.

If you want to be sure, the simplest way is to check using prints along the way, checking constantly for the state of a thing to happen

Answered By: XxJames07-
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.