HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

"Increment" a string of uppercase characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
charactersincrementstringuppercase

Problem

Given a string of uppercase characters, return a string corresponding to the next item in the following series:

A, B, ..., Z, AA, AB, ..., AZ, BA, ..., BZ, ..., ZZ, AAA, ...


My code:

def increment_char(c):
    """
    Increment an uppercase character, returning 'A' if 'Z' is given
    """
    return chr(ord(c) + 1) if c != 'Z' else 'A'

def increment_str(s):
    lpart = s.rstrip('Z')
    if not lpart:  # s contains only 'Z'
        new_s = 'A' * (len(s) + 1)
    else:
        num_replacements = len(s) - len(lpart)
        new_s = lpart[:-1] + increment_char(lpart[-1])
        new_s += 'A' * num_replacements
    return new_s


Proof my code works according to the specification I gave above:

In [4]: increment_str('A')
Out[4]: 'B'

In [5]: increment_str('Z')
Out[5]: 'AA'

In [6]: increment_str('AA')
Out[6]: 'AB'

In [7]: increment_str('AZ')
Out[7]: 'BA'

In [8]: increment_str('ZZ')
Out[8]: 'AAA'


One thing I would ask you ignore is whether or not you think s and new_s (but only those two) are good names for identifiers, because they are not present in the real code (only the trimmed down version for here). All other suggestions, bug reports, etc., are welcome.

Solution

A slight simplification of the if else structure is possible:

def increment_str(s):
    lpart = s.rstrip('Z')
    num_replacements = len(s) - len(lpart)
    new_s = lpart[:-1] + increment_char(lpart[-1]) if lpart else 'A'
    new_s += 'A' * num_replacements
    return new_s

Code Snippets

def increment_str(s):
    lpart = s.rstrip('Z')
    num_replacements = len(s) - len(lpart)
    new_s = lpart[:-1] + increment_char(lpart[-1]) if lpart else 'A'
    new_s += 'A' * num_replacements
    return new_s

Context

StackExchange Code Review Q#100865, answer score: 3

Revisions (0)

No revisions yet.