Как создать пароль из 4 цифр в python? - PullRequest
2 голосов
/ 12 февраля 2020

Я создаю клавишу 4 di git alphanumeri c, где символы начинаются с A001, A002 до Z999. После Z999 он переходит на AA01 до AA99. После AA99 он переходит к AB00 или AB01. Проблема, с которой я сталкиваюсь, заключается в том, что когда я увеличиваю диапазон, после AA99 он не идет к AB01. Он начинается снова с AA01 и заканчивается AA99, и то же самое продолжает повторяться. Любая помощь в этом отношении будет оценена.

Большое спасибо!

Что я пробовал -

    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))

1 Ответ

2 голосов
/ 12 февраля 2020

Ниже преобразует 0-92897 из A001-Z999, AA01-ZZ99 и печатает точки прокрутки для демонстрации:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...