Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading