I am practicing for an interview and one of the past questions asked to the interviewes is to - "Write a program that increments the alphabet such that A becomes B, Z becomes AA, and ABZ becomes ACA."
I need help on understanding how I could achieve the intended result. I tried using a simple function which increments the Ascii value and can certainly get the result using if loop with the chracter "z" as a special case.
def give_string(random_string):
word = ""
for i in range(len(random_string)):
if(random_string[i] == 'z' or random_string[i] == 'Z'):
#if "z or Z" is at the begining of the string
if(random_string[0] == 'z' or 'Z' and i == 0):
if(i == 'z'):
word = word + 'aa'
else:
word = word + 'AA'
if(len(random_string) == 1):
return word
# if the last character is "z or Z", we also need to change the first character to a or A
# i.e., BCZ = ADA not CDAA
elif(random_string[-1] == 'z' or 'Z' and i == (len(random_string) - 1)):
if(random_string[-1] == 'z'):
word = word + 'a'
word = word[:0] + 'a' + word[0+1:]
else:
word = word + 'A'
word = word[:0] + 'A' + word[0+1:]
return word
#if "z or Z" is somewhere in the middle of the string
else:
print("going to the middle")
if(random_string[i] == 'z'):
word = word + 'aa'
else:
word = word + 'AA'
#if it is any character other than "z or Z"
else:
word = word + chr(ord(random_string[i])+1)
return word
if __name__ == '__main__':
my_string = "ZbgsGD"
print(my_string)
print(give_string(my_string))
However, what I want to know is, is there some other way to solve this that I am missing,
As you can see the code does do the job of getting the correct result. I just want to know if there is any other simpler way to achieve the intended result that I am missing, cause using all these loops does not seem like the best way to do this.