Addition of chars adding one character in front
algorithm, python
Solution
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
Problem
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 ?