Home > Blockchain >  Recursion through List: Why is it returning None and giving separate lines?
Recursion through List: Why is it returning None and giving separate lines?

Time:10-29

I am figuring out a problem that goes through a list of strings, takes the first letter of each string and turns everything into an abbreviation of all the words in the list. So for example,

print(recAbbrev(['central','processing','unit']))

should return

'CPU'

Here is my code as of right now:

def recAbbrev(lst):
    'return a single string with the first character of all the strings in a list combined and capitalized.'
    if len(lst)==0:
        print('')
        return
    
    if len(lst)>0:
        if type(lst[0])==list:
            recAbbrev(lst[0])
        else:
            acronym = ""
            letter = ""
            letter = letter   lst[0][:1]
            letter = letter.upper()
            #lst.pop[0]
            acronym = acronym   letter
            print(acronym)  
            recAbbrev(lst[1:])

I am having two problems that I can't seem to understand with this code. First, I want my base case to return '' in the case of an empty list. Instead, it returns None. How can I work around this? Here is my output:

Starting recAbbrev

None
C
P
U

This is a simple question, but how can I get everything to stay on one line? It seems like recursion is trying to keep me from doing this.

CodePudding user response:

You are printing values and returning nothing. you have to modify you function:

def recAbbrev(lst):
    'return a single string with the first character of all the strings in a list combined and capitalized.'
    if len(lst)==0:
        return ''
    if len(lst)==1:
        return lst[0][0].upper()
    else:
        return lst[0][0].upper() recAbbrev(lst[1:])

then test it:

lst = ['central','processing','unit']

recAbbrev(lst)

CodePudding user response:

A simpler solution can be the following, unless you must use a recursion because this is a homework:

def recAbbrev(lst):
    return "".join([w[0].upper() for w in lst])

lst = ['central','processing','unit']
print(recAbbrev(lst))

Output:

CPU

This works also if the list is empty and in this case it returns en empty string.

CodePudding user response:

print has a default \n character at the end of the printed string (see the documentation here). Change print(acronym) to print(acronym, end='')

You are getting the None because you are printing recAbbrev, which has no return and therefore defaults to returning None. Just call recAbbrev(['central','processing','unit'])

  • Related