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.
increment_strisn't dealing with strings like 'AA', 'AB', etc. It's dealing with longer strings and parsing that bit out. I have removed all the code dealing with the rest of that string and presented a simpler function. The code is exact except for the two changes I mentioned in the post, just out of context. This is also whyincrement_strdoesn't have a docstring here. \$\endgroup\$intfunction uses 'A-Z' as the base 26 "digits".int('Z', 26)raises aValueErrorfor me in Python 2.7. \$\endgroup\$