-2

I am trying to make a number generator for a project I am working on, and I need every number to be unique. The range is '0-100000'. I have the following:


    for i in range (1,100000):
        num = random.randint(0, 100000)
        store = num
        print (num)
        num = random.randint(0, 100000)
        if num == store:
            num = '-'
        print(num)

I can't go through all the outputs in a timely manner, but at a glance, I have seen two issues with them. Firstly, there are repeats, because 'store' gets changed every time, and is only one number. Secondly, one of the outputs, on my current output screen, is '4183053688'. The range doesn't allow for that, so I don't know what happened.

I have only thought of two possible answers. Firstly I have played around with making a list to check whether a number has been used or not, but I haven't found a way to update it as numbers come in, and I will be using so many number in a short time, that manually putting them in is impractical. My second idea is what the code shows. But those problems have already been explained.

3 Answers3

2

random.sample with range specified does the job for your reference

import random
unique_numbers = random.sample(range(0, 100001),100000)
print(unique_numbers)
yashaswi k
  • 668
  • 7
  • 17
0

So what you're saying is that you want all the numbers in a range returned in a random order. Therefore:

from random import shuffle

def func(r: range) -> list[int]:
    _list: list[int] = list(r)
    shuffle(_list)
    return _list

print(func(range(100_000)))

Note:

This will return a list comprised of all values in the range. If you don't need the full list then just slice it

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

You asked me to explain the "set" solution to this problem in comment. So this is a possible solution:

s = set()
while len(s) < 100:
    s.add(random.randint(0, 1000))

A set is an unordered collection without duplicates, so you cannot add the same number multiple times.

The code above add random numbers to the set called s until its length reaches your target length. But you must be sure to request less or equal numbers than the input range of the randint function or you will run into an infinite loop. Also avoid to request roughly the same length of the input range or you will simply get [0, 1, 2, 3, ...] which will be a unique list but not really random...

In performance it is not the best. Up to a few hundred thousand elements it can finish in a fraction of a second. But as you increase the required random numbers your runtime will explode.

simre
  • 647
  • 3
  • 9