I've always liked uuid4 >>> from uuid import uuid4 >>> str(uuid4())[:4] '0ca6'
On Tue, Jun 26, 2012 at 3:47 PM, Dave Angel <d...@davea.name> wrote: > On 06/26/2012 03:47 PM, Martin A. Brown wrote: > > Hello, > > > > : Would anyone have tips on how to generate random 4-digit > > : alphanumeric codes in python? Also, how does one calculate the > > : number of possible combinations? > > > > Here are some thoughts that come to my mind: > > > > import string > > import random > > > > # -- technique #1, using random.choice > > print ''.join([random.choice(string.lowercase) for x in range(4)]) > > > > # -- technique #2, using random.shuffle > > t = [ x for x in string.lowercase ] > > random.shuffle(t) > > ''.join(t[0:4]) > > > > # -- technique #3, using random.sample > > ''.join(random.sample(string.lowercase,4)) > > > > I would be quite surprised if there were not more efficient ways of > > accomplishing this. > > > > -Martin > > > Two problems that I see: > > string.lowercase includes the lowercase letters, but not the digits. > > Your methods 2 and 3 produce different results than method1. The OP > never specified which he wanted, but the distinction can well be important. > > Likewise his query about how many possibilities there are depends on the > same question: > Are duplicates permitted between the four characters in any given > answer. > > > > > -- > > DaveA > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor