简体   繁体   中英

Why my code return a Type error of unsupported operand type(s) for +: 'NoneType' and 'list'

I wang to reserve a char list by recursion in python, but I get a type error in the last step, I don't know why this happened. I will appreciate you

def reverseString(s):
    if len(s) ==1:
        s
    else:
        reverseString(s[1:])+list(s[0])

input like ['a','b','c','d'] ,

expected output ['d','c','b','a']

there is a type error :

unsupported operand type(s) for +: 'NoneType' and 'list'

You forgot to return something in your function. If you do not return something explicitly, Python will implicitly return None .

It might be better to check if the string has a length that is zero (so the empty string), such that your function can reverse an empty string as well:

def reverseString(s):
    if not s:
         s
    else:
         reverseString(s[1:])+s[0]

For example:

>>> reverseString('foobar')
'raboof'

Using recursion, especially linear recursion is not a good idea here, since the call stack grows with the length of the string, and thus for not so small strings, you will get a stackoverflow.

You can make use of the reversed(..) iterator of a string, and thus return the reversed string with:

>>> ''.join(reversed('foobar'))
'raboof'

this is especially useful if you want to iterate over the string in reverse, without constructing one (for example when processing the individual characters in reverse).

or through slicing, as @Austin says:

>>> 'foobar'[::-1]
'raboof'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM