Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition of chars adding one character in front

what I'm trying to implement is a function that increments a string by one character, for example:

'AAA' + 1 = 'AAB'
'AAZ' + 1 = 'ABA'
'ZZZ' + 1 = 'AAAA'

I've implemented function for the first two cases, however I can't think of any solution for the third case.

Here's my code :

def new_sku(s):
    s = s[::-1]
    already_added = False
    new_sku = str()

    for i in s:
        if not already_added:
            if (i < 'Z'):
                already_added = True
            new_sku += chr((ord(i)+1)%65%26 + 65)
        else:
            new_sku += i

    return new_sku[::-1]

Any suggestions ?

like image 843
Marijus Avatar asked Jul 31 '13 08:07

Marijus


2 Answers

If you're dealing with bijective numeration, then you probably have (or should have) functions to convert to/from bijective representation anyway; it'll be a lot easier just to convert to an integer, increment it, then convert back:

def from_bijective(s, digits=string.ascii_uppercase):
    return sum(len(digits) ** i * (digits.index(c) + 1)
               for i, c in enumerate(reversed(s)))

def to_bijective(n, digits=string.ascii_uppercase):
    result = []
    while n > 0:
        n, mod = divmod(n - 1, len(digits))
        result += digits[mod]
    return ''.join(reversed(result))

def new_sku(s):
    return to_bijective(from_bijective(s) + 1)
like image 103
ecatmur Avatar answered Oct 08 '22 13:10

ecatmur


How about ?

def new_sku(s):
    s = s[::-1]
    already_added = False
    new_sku = str()

    for i in s:
        if not already_added:
            if (i < 'Z'):
                already_added = True
            new_sku += chr((ord(i)+1)%65%26 + 65)
        else:
            new_sku += i

    if not already_added: # carry still left?
        new_sku += 'A'

    return new_sku[::-1]

Sample run :-

$ python sku.py Z
AA
$ python sku.py ZZZ
AAAA
$ python sku.py AAA
AAB
$ python sku.py AAZ
ABA
like image 23
Himanshu Avatar answered Oct 08 '22 14:10

Himanshu