0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

アルファベットからなる連続IDを生成するPythonコード

Posted at

概要

SpreadSheetのカラム名のように、A, B, C, ...., Z, AA, AB, AC, ADと連続するIDを生成するコードを作成した

コード

なお今回は、Aを自然数における0と同じ様に扱うように設定した。つまり以下となる。

  • 正) Y → Z → BA → BB
  • 誤) Y → Z → AA → AB

これは、8 → 9 → 00ではなく、8 → 9 → 10であることに等しい

import string

ZERO_CHAR = 'A'
ONE_CHAR = 'B'
LAST_CHAR = 'Z'
CHAR_SERIES = string.ascii_uppercase


def reverse(_list):
    return list(reversed(_list))


def succ(char):
    alphabet_to_num = dict(zip(CHAR_SERIES, [i for i in range(1, len(CHAR_SERIES) + 1)]))
    num_to_alphabet = {v: k for k, v in alphabet_to_num.items()}

    succ_index = alphabet_to_num[char] % len(CHAR_SERIES) + 1
    return num_to_alphabet[succ_index]


def succ_list(_list):
    # 繰り上がりして桁が増えた場合はONE_CHAR(==B)になる
    if len(_list) == 0:
        return [ONE_CHAR]
    # LAST_CHAR(==Z)の場合は繰り上がる
    elif _list[0] == LAST_CHAR:
        return [ZERO_CHAR] + succ_list(_list[1:])
    else:
        return [succ(_list[0])] + _list[1:]


def succ_code(previous_code):
    return ''.join(reverse(succ_list(reverse(list(previous_code)))))


def gen_code(init_code='AA', limit=10):
    code = init_code
    for _num in range(0, limit):
        yield code
        code = succ_code(code)

LIMIT = 10

for x in gen_code(init_code='ZX', limit=LIMIT):
    print(x)
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?