Search code examples
pythonfunctionrecursionascii

Converting lowercase to uppercase in Python using recursion


I am a student relatively new to Python, learning it through classes. We were given a question where we have a list as an input, and we have to convert each element to uppercase. Here is my code so far:

def strChange(lst):
    ch=''
    for i in range(len(lst)):
        if lst[i]>='a' and lst[i]<='z' :
            ch+=chr(ord(lst[i])-32)
    return ch
caps =  eval(input("Enter list: "))
caps2 = []
for i in range(len(caps)):
    a = strChange(caps[i])
    caps2.append(a)
print(caps2)

And it does the job... But the problem is, it is not using recursion! And I have absolutely no idea where to use it! I am open to all suggestions, but layman's terms are preferred.

Edit: adding example inputs

input: ['rohit', 'mohan', 'anjali', 'ankit', 'akshit']

output: ['ROHIT', 'MOHAN', 'ANJALI', 'ANKIT', 'AKSHIT']


Solution

  • It's silly, but here's how you do it. You process one character and call the function again for the rest.

    def strChange(lst):
        if not lst:
            return ''
        ch = lst[0]
        if 'a' <= ch <= 'z':
            ch = chr(ord(ch)-32)
        return ch + strChange(lst[1:])
    caps =  eval(input("Enter list: "))
    for word in caps:
        print(strChange(word))