Random Sequence Generator in Python

I needed to generate random numbers but in sequence within a certain range. For example, I could generate 10,000 numbers in the range of 1000 to 9999. Rather than generate this range in sequence, I needed to generate this sequence randomly. For this exercise, random is your friend. How did I do it? The code is as below:

from random import randrange, shuffle

randomlist = []
uniqueflag = False
total_to_generate = 40000
start_range = 10000
end_range = 99999

for i in xrange (1,total_to_generate+1):
    while not uniqueflag:
        randomnumber = randrange(start_range,end_range)
        if randomnumber not in randomlist and randomnumber not in (11111, 22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999):
            uniqueflag = True
    randomlist.append(randomnumber)
    uniqueflag = False
shuffle(randomlist)
for x in randomlist:
    print x

You can change total_to_generate, start_range, and end_range according to your needs. I chose to exclude 11111, 22222, and so on, because they are the easiest to guess and if you need random numbers, better to exclude them. I also chose to shuffle to add a bit more randomness.

I named the file rando.py and used it as below. Since the code prints to standard output, I chose to redirect the output to a file to save the numbers.

python rando.py > numbers.txt

Hat tip to: How do I generate random numbers in Python?; shuffling elements of a list.

About these ads

One Response to Random Sequence Generator in Python

  1. Great job…
    tks…
    i´ll copy to my python code library…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 30 other followers

%d bloggers like this: