0

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.

Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
J_B
  • 9
  • 3
  • 1
    The rules contradict - if `Z` becomes `AA`, shouldn't `ABZ` become `BCAA`? Otherwise there's a load of extra logic needed to check for single `Z`s on their own? – Luke Nov 02 '22 at 15:53
  • 1
    Think of the strings as a counting system, A > B > C..... Z > AA > AB....... – KillerRebooted Nov 02 '22 at 15:55
  • According to the instructions if the z is at the end of the string i.e., the last character, you have to change the first letter of the returnd string with that second A from Z = AA. For example HBZ "should be" ICAA" but that second A replaces the first character "I" so the answer is ACA – J_B Nov 02 '22 at 15:57
  • 1
    `random_string[0] == 'z' or 'Z' and i == 0` is wrong because it is NOT `random_string[0] == ('z' or 'Z')`. It is interpreted as `(random_string[0] == 'z') or ('Z' and i == 0)` and 'Z' there is interpreted as bool('Z'), so True. Therefore this all changes to `random_string[0] == 'z' or i == 0` – h4z3 Nov 02 '22 at 15:59
  • @h4z3 thank you for that I didnt realize I forgot the brackets. – J_B Nov 02 '22 at 16:04
  • Looks like instead of base2, base10 or base64, you're looking to develop something that is base26. Then you can take in a AGIZ and then add or subtract HUG from it. You would need to develop a parser to take in a String and then add actions to it. – Fallenreaper Nov 02 '22 at 16:05
  • @J_B even with brackets `random_string[0] == ('z' or 'Z')` is incorrect python and will mean only `random_string[0] == 'Z'`, I was just trying to interpret what you thought it meant but forgot to correct it, this is one of the common beginner problems. Do either `random_string[0] in ('z', 'Z')` or `random_string[0].lower() == 'z'` – h4z3 Nov 02 '22 at 16:07
  • @h4z3 okay that makes sense, I replaced it with random_string[0] in ('z', 'Z'). Once again thank you for the correcetion. – J_B Nov 02 '22 at 16:15

1 Answers1

0

Appears similar to Potential interview question: building a pseudocode string incrementer similar to Excel columns

Essentially, it asks to build a string incrementer so that A + 1 = B... Z + 1 = AA, AA + 1 = AB... ZZ + 1 = AAA... and so forth.

Code

def incr(s):
    '''
        Incremental for string s
        
    '''
    def incr_chr(c):
        '''
            Helper function that provides single character incrementer
        
           carry and next character for character incrment
        '''
        if c in ('z', 'Z'):
            return 1, 'a' if c.islower() else 'A'          # with carry one
        else:
            return 0, chr(ord(c) + 1) # with carry zero
        

    lst = list(s)                            # string to list since string immutable
    result = []
    while lst:
        carry, next_ = incr_chr(lst.pop())   # increment last letter in list
        result.append(next_)                 # add last incremented character to result

        if not carry:                        # break if no carry
            break
        if not lst:
            result.append('a' if next_.islower() else 'A')  # empty lst but remaining carry
            
    result += lst[::-1]                      # add remainder of string list to result
    
    return ''.join(result[::-1])             # list to string in reverse order
 

Test

for t in  ['a', 'A', 'b', 'z', 'Z', 'ABZ', 'abz', 'abcdz', 'ZbgsGD', 'zzz', 'ZZ']:
    print(f'{t} -> {incr(t)}')

Output

a -> b
A -> B
b -> c
z -> aa
Z -> AA
ABZ -> ACA
abz -> aca
abcdz -> abcea
ZbgsGD -> ZbgsGE
zzz -> aaaa
ZZ -> AAA
​
DarrylG
  • 16,732
  • 2
  • 17
  • 23