Home > Blockchain >  Converting lowercase to uppercase in Python using recursion
Converting lowercase to uppercase in Python using recursion

Time:12-13

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

CodePudding user response:

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))

CodePudding user response:

Maybe you can use recursion in case of nested lists? If item in list is list you call same function with it?

def strChange(lst):
    for index, item in enumerate(lst):
        if type(item) is list:
            strChange(item)
        else:
            lst[index] = item.upper()
    return lst
  • Related