[Tutor] Generate 8 digit random number

Jacob S. keridee at jayco.net
Sat Sep 3 02:27:29 CEST 2005


> Hey Tutors
>
> I saw a lot of responses...After analyze them I have resumed two 
> approaches
>
> 1.- Generate a random number from 0 to 99999999 and fill this number with
> zeros (Almost everyone's approach)
> 2.- Generate 8 random numbers and join them (Pietro and someone else)
>
> Which one of this is more randomic? I mean which one of these has lower
> chances to get duplicates?
> Until now I'm using approach number 2.......Unless anyone has something
> against it...

Frankly,
    I would probably prefer #1 because it's probably faster. (You're just 
generating one number, and calling 1or 2 functions on it as opposed to at 
least 1 random and 1 function for each digit)

Secondly, in both cases, there is the chance that you will get duplicates~~
So the best way to do that is save passwords already generated in a list.

######  Try this #######

import random
import cPickle  ## This is to save passwords already generated between 
program runs.

def getlist():
    try:
        fileobj = file("passwords.lst","r")
        returnlist = cPickle.load(fileobj)
        fileobj.close()
    except IOError:
        returnlist = []
    return returnlist

def generate():
    return str(random.randrange(0,99999999)).zfill(8)  ## Not that this is 
the best, but it is concise

def close(li):
    obj = file("passwords.lst","w")
    cPickle.dump(li,obj)
    obj.close()


masterlist = getlist()

num = 0
while 1:
    while num in masterlist:
        num = generate()
    masterlist.append(num)
    print num
    m = raw_input()
    if m == 'quit':
        close(masterlist)
        break
######################

Okay, I believe it will work, I haven't tested it though. Any problems, 
grouch at me, please.

Respectfully,
Jacob 



More information about the Tutor mailing list