[Tutor] All possible 16 character alphanumeric strings?

Dave Angel d at davea.name
Sun Sep 16 02:01:32 CEST 2012

On 09/15/2012 06:50 PM, Scurvy Scott wrote:
> Hello again python tutor list.
> I have what I see as a somewhat complicated problem which I have no idea
> where to begin. I'm hoping you fine folks can help me.
> I'm trying to generate a list of every possible 16 character string
> containing only 2-7 and a-z lowercase.

That list would fill all the PC's on the planet a few billions times. 
The number of items in the list has 25 digits in it.  print 32**16

>  I've seen some examples using regex

Not likely to be the least bit useful.

> to define which characters I want to use but not a way to generate the
> complete list of all possibilities. I'm not looking for a handout- just a
> point in the right direction.
> Any information would be awesome, thanks.
> Right now I've got something like:
> import random
>>>> ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in range(16))

You said you wanted a list with every possible string, not a list of
random strings.

> Which only prints 1 number, obviously.
> or possibly something like this:
> def genKey():
>     hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32")
>     alnum_hash = re.sub(r'[^a-z2-7]', "", hash)
>     return alnum_hash[:16]

still random, does not apply to the problem as stated.

> Keeping in mind that although I understand this code, I did not write it, I
> got it from stackoverflow.
> Again any help would be great. Feel free to ask if you must know exactly
> what I'm trying to do.
> I'm running Ubuntu 12.04 and python 2.7
> Scott

If you wanted to use a smaller string, or a smaller set of characters,
so that it might be actually possible to list ALL the possibilities,
then start with Peter Otten's code using itertools.product().

import itertools
chars = "ab5"
result = ["".join(item) for item in product(*[chars]*4)]

print len(result)

This one only has 81 items in it ( 3**4 )  so it's quite workable.

if you want to see the first seven items:

for item in result[:7]:
    print item




More information about the Tutor mailing list