Generate alphanumeric strings sequentially

I am trying to create a loop to generate and print lines as follows:

  • Alphanumeric characters:
  • 0-9 are in front of AZ, which are in front of az,
  • Length - up to 4 characters.

So he will print:

  • all rows from 0-z
  • then from 00-zz
  • then from 000-zzz
  • then from 0000-zzzz

then he stops.

+5
source share
3 answers
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product

chars = digits + ascii_uppercase + ascii_lowercase

for n in range(1, 4 + 1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

First, a string is created from all numbers, uppercase and lowercase letters.

Then, for each length from 1 to 4, he prints all possible combinations of these numbers and letters.

Keep in mind that these are LOTS of combinations - 62 ^ 4 + 62 ^ 3 + 62 ^ 2 + 62.

+17
source

, , product, , python, , , , .

, , agf, ( ). yield - , , ( range, xrange ).

:

def generate(chars, length, prefix = None):
    if length < 1:
        return
    if not prefix:
        prefix = ''
    for char in chars:
        permutation = prefix + char
        if length == 1:
            yield permutation
        else:
            for sub_permutation in generate(chars, length - 1, prefix = permutation):
                yield sub_permutation

, , , "n", "n" - ( 4), .

chars - , 4, , , .

0

I encoded it today. He does exactly what you need and more . It is also expanding.

def lastCase (lst):
    for i in range(0, len(lst)):
        if ( lst[i] != '_' ):
            return False
    return True


l = [''] * 4 #change size here if needed. I used 4
l[0] = '0'
index = 0

while ( not lastCase(l) ):

    if ( ord(l[index]) > ord('_') ):
        l[index] = '0'
        index += 1
        while( l[index] == '_' ):
            l[index] = '0'
            index += 1
        if (l[index] == ''):
            l[index] = '0'

    #print or process generated string
    print(''.join(l))

    l[index] = chr(ord(l[index]) +1)

    if ( ord(l[index]) > ord('9') and ord(l[index]) < ord('A') ):
        l[index] = 'A'
    elif ( ord(l[index]) > ord('Z') and ord(l[index]) < ord('_')  ): 
        l[index] = '_'

    index = 0

print (''.join(l))
0
source

All Articles