samedi 2 juillet 2016

Incrementing string in Python


I am writing a function to increment a 3-letter (a-z) string. For example:
Input: aaa
Output: baa

Input: zba
Output: aca

So the order is as following

aaa
baa
...
zaa
aba
bba
cba
...
zba
aca
bca
cca
...
zca
ada
...
zzz
aaa

I wrote the following function next_code() and it works, but I am wondering if there is a more elegant way to implement it rather than looping through individual letters in the string:

# 0 = a; 25 = z
def digit_to_char(digit):
    return chr(ord('a') + digit)

# a = 0; z = 25
def char_to_digit(char):
    return ord(char)-ord('a')

def next_code(code):
    # if used up all codes, loop from start
    if code == 'zzz':
        return next_code('aaa')
    else:
        code = list(code)
        # loop over letters and see which one we can increment
        for (i, letter) in enumerate(code):
            if letter == 'z':
                # go on to the next letter
                code[i] = 'a'
                continue
            else:
                # increment letter
                code[i] = digit_to_char(char_to_digit(letter) + 1)
                return ("".join(code))
                break



print (next_code('aab'))

Aucun commentaire:

Enregistrer un commentaire