Search code examples
pythoncharacterauto-incrementalphanumeric

How to create a passkey of 4 digits in python?


I am designing a 4 digit alphanumeric key where the characters starts from A001, A002 till Z999. After Z999 it goes to AA01 till AA99. After AA99 it goes to AB00 or AB01 . The problem which I am facing is when I increase the range, after AA99 it is not going to AB01. It start again with AA01 and ends at AA99 and the same thing keep on repeating. Any help regarding this will be appreciated.

Many Thanks!

What I tried -

    def excel_format(num):
    res = ""
    while num:
        mod = (num - 1) % 26
        res = chr(65 + mod) + res
        num = (num - mod) // 26
    return res

def full_format(num, d=3):
    chars = num // (10**d-1) + 1 # this becomes   A..ZZZ
    c = excel_format(chars)
    digit = num %  (10**d-1) + 1 # this becomes 001..999

    return c + str(digit).zfill(d+1-len(c))[len(c)-d-1:]

for i in range(0, 28000):
    print(full_format(i, d=3))

Solution

  • Below converts 0-92897 from A001-Z999, AA01-ZZ99 and prints rollover points for demonstration:

    def full_format(i):
        # limit of first range is 26 letters (A-Z) times 999 numbers (001-999)
        if i < 26 * 999:
            c,n = divmod(i,999)   # quotient c is index of letter 0-25, remainder n is 0-998
            c = chr(ord('A') + c) # compute letter
            n += 1
            return f'{c}{n:03}'
        # After first range, second range is 26 letters times 26 letters * 99 numbers (01-99)
        elif i < 26*999 + 26*26*99:
            i -= 26*999               # remove first range offset
            cc,n = divmod(i,99)       # remainder n is 0-98, use quotient cc to compute two letters
            c1,c2 = divmod(cc,26)     # c1 is index of first letter, c2 is index of second letter
            c1 = chr(ord('A') + c1)   # compute first letter
            c2 = chr(ord('A') + c2)   # compute second letter
            n += 1
            return f'{c1}{c2}{n:02}'
        else:
            raise OverflowError(f'limit is {26*999+26*26*99}')
    
    # Generate all possibilities into a list for demonstration.
    L = [full_format(i) for i in range(92898)]
    
    print(L[0])
    print(L[999-1])
    print(L[999])
    print(L[26*999-1])
    print(L[26*999])
    print(L[26*999+99])
    print(L[26*999+99*26-1])
    print(L[26*999+99*26])
    print(L[26*999+99*26*26-1])
    full_format(92898) # overflow
    
    A001
    A999
    B001
    Z999
    AA01
    AB01
    AZ99
    BA01
    ZZ99
    Traceback (most recent call last):
      File "C:\test.py", line 31, in <module>
        full_format(92898) # overflow
      File "C:\test.py", line 18, in full_format
        raise OverflowError(f'limit is {26*999+26*26*99}')
    OverflowError: limit is 92898