Recursive function to return string backwards

Asked

Viewed 2,726 times

1

I need a recursive function that returns the string it takes as the inverted form parameter,arrived in this role:

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

print(stringinvert('teste'))

But it creates an error that in this case is this one:

if palavra < 10:

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

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

2 answers

8


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

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

But even then it wouldn’t work, going into infinite cycle if the string length was less than 10 characters, or returning None if it were 10 or more characters.

To reverse 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

DEMONSTRATION

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

'aeiou'[::-1]
  • Always learning, never knowing [::-1]. By the way, can you explain the difference between [:] and [::]? :)

  • 1

    @lazyFox, look at it this way, lista[index_start:index_end:step], and where the step can be negative, generating the inverted list in case it is -1. Here are more complete explanations: https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation

  • 1

    Thank you @Miguel :) very useful this link.

0

You are returning this error because the 'word' is a string and not a number to use a comparator as the smallest (<).

In this case just add the 'Len' function that will return the string size.

Follows code below:

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

print(stringinvert('teste'))
  • 2

    For the record, I left my negative because the solution is wrong. Just add the len didn’t solve the problem. Its recursive function has no stop condition, making it infinitely recursive, and making no sense of the code.

  • Anderson, my answer was exactly in the doubt of our colleague. Which I knew to answer, as to non-recursiveness had not seen such a problem. The question of the answer not affecting these two points is why it was not requested, I do not know to what extent it deserves negativity. But I understand your position and thank you for the feeback

  • 1

    I didn’t deny it, but you’re wrong: RecursionError: maximum recursion depth exceeded in comparison

  • 1

    Clayton, as I said up there, The problem is that this solution of yours doesn’t give a base case for recursive function, exactly what Anderson said.Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.