-4

This is probably a duplicate of something, but oh well. I'm trying to create a random number generator that goes over all 7 digit numbers (0000001 - 9999999) but I'm having issues thinking how I'd code such a mechanism; would anyone know any libraries or functions that may help here?

Edit: Big thanks to Kelly Bundy and Alexpdev for helping me understand how I can code this script

Nexus
  • 23
  • 4
  • 3
    `but I'm having issues...`. Can you give an example of the issues you are having? When you says `goes over all` does that mean you want to output 10 million values? Or are you only trying to generate a single (or a few) value(s) from that range? As far as libraries...well there is [random](https://docs.python.org/3/library/random.html). – Mark Feb 15 '22 at 02:13
  • What are you going to do with that? – Kelly Bundy Feb 15 '22 at 02:21
  • Are you looking for a manual solution so you can understand the code for such a problem, or are you looking for an out-of-the-box solution you can use in your other code? – PeptideWitch Feb 15 '22 at 02:21
  • Keep track of the numbers you've already generated. If you generate a duplicate, just try again. What is the difficulty? – John Gordon Feb 15 '22 at 02:28

2 Answers2

0

In addition to the answers linked in the original post comment section, you can also use numpy to generate an array of x length and randomise the order:

import numpy as np

x = 10000000
a = np.arange(x)  
np.random.shuffle(a)
print(a)

This is the example straight from numpy's website

np.arange(x) creates an array from 0 to x-1, stepped at 1. Numpy can then shuffle your array inplace.

Beyond 9 digits, this answer becomes unfeasible due to memory limitations, in which case you'd simply be better off using a generator or RNG function.

If you want to format your number as a string and fill it with padding zeros, eg 0000020 instead of 20, you can do:

str(a[idx]).zfill(7)
PeptideWitch
  • 2,239
  • 14
  • 30
0

Using the random module that comes with python you can use the randint function to get a random integer in the range of it's arguments.

Then cast the result to a str and pad it with "0"s for the desired output.

import random

def get_random_sequence():
    num = random.randint(0,9999999)
    return str(num).rjust(7,"0")
Alexander
  • 16,091
  • 5
  • 13
  • 29