Recursive function to return string in reverse

1

I need a recursive function that returns the string that it receives as a parameter inverted , I got this function:

def stringinvert(palavra):
    if palavra < 10:
        print(palavra)
        return stringinvert(palavra[::-1])

print(stringinvert('teste'))

But it generates an error that in this case is this:

if palavra < 10:

    TypeError: '<' not supported between instances of 'str' and 'int'

Well, that was foreseeable for me. The question is: the recursive step is the string having only one letter, ie I return only this letter, the problem is how will I create this condition in Python?

    
asked by anonymous 23.04.2018 / 17:21

2 answers

7

The error is happening because you are checking if "test" (string) is less than 10 (???), I think what you want is the length of the string (number of characters):

...
if len(palavra) < 10:
...

But it still would not work, going into an infinite loop if the length of the string was less than 10 characters, or returning None if it was 10 or more characters.

To make the inversion of the string using recursion you can:

def reverse_str(s):
    if s == '':
        return s # retornar invertida
    return s[-1] + reverse_str(s[:-1]) # concatenar o ultimo caracter com o resto da string excepto o ultimo

print(reverse_str('aeiou')) # uoiea

STATEMENT

Note that this is only for pedagogical reasons, because in the 'real world' the best thing to do is:

'aeiou'[::-1]
    
23.04.2018 / 18:17
0

You are returning this error because the 'word' is a string and not a number to use a comparator as the lesser than (

23.04.2018 / 17:33