LoginSignup
1
2

More than 5 years have passed since last update.

Python | マジカルインクリメント

Last updated at Posted at 2017-06-13

マジカルインクリメント

# -*- using:utf-8 -*-

import re


def magical_increment(start):
    pattern = re.compile(r'[^0-9A-Za-z]')

    while True:
        yield start

        temp = []
        add = 1
        carry = None

        for c in reversed(list(start)):
            if pattern.match(c):
                temp.append(c)
                continue

            ch = chr(ord(c) + add)
            if c <= '9' < ch:
                ch = '0'
                carry = '1'
            elif c <= 'Z' < ch:
                ch = carry = 'A'
            elif c <= 'z' < ch:
                ch = carry = 'a'
            else:
                add = 0
                carry = None
            temp.append(ch)

        if carry:
            temp.append(carry)

        start = ''.join(reversed(temp))


if __name__ == '__main__':
    gen = magical_increment('Az-8')
    for i in range(5):
        print(next(gen))

英数字のみインクリメントします。記号はそのままです。

Az-8
Az-9
Ba-0
Ba-1
Ba-2

マジカルAdd

# -*- using:utf-8 -*-

import re


def magical_add(start, step):
    pattern = re.compile(r'[^0-9A-Za-z]')

    while True:
        yield start

        temp = []
        add = step
        prev = ''

        for c in reversed(list(start)):
            if pattern.match(c):
                temp.append(c)
                continue

            if c <= '9':
                value = ord(c) + add % 10
                add //= 10
                prev = '0'
                if ord('9') < value:
                    value -= 10
                    add += 1
            elif c <= 'Z':
                value = ord(c) + add % 26
                add //= 26
                prev = 'A'
                if ord('Z') < value:
                    value -= 26
                    add += 1
            else:
                value = ord(c) + add % 26
                add //= 26
                prev = 'a'
                if ord('z') < value:
                    value -= 26
                    add += 1

            temp.append(chr(value))

        if add:
            if prev == '0':
                temp.extend(reversed(list(str(add))))
            elif prev == 'A' or prev == 'a':
                while add:
                    value = ord(prev) + add % 26 - 1
                    add //= 26
                    temp.append(chr(value))

        start = ''.join(reversed(temp))


if __name__ == '__main__':
    gen = magical_add('aZ-1', 5)
    for i in range(5):
        print(next(gen))

英数字のみ加算します(この例では5加算しています)。記号はそのままです。

aZ-1
aZ-6
bA-1
bA-6
bB-1
1
2
2

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
1
2