RE: How to write this iterative function to be recursive in python?

I need to write this iterative function to do the same thing but it must be recursive.
def task1(string: str):
    for i in range(len(string)):
        if string[i] != string[len(string) - i - 1]:
            return False
    return True

This is what i tried but it does not work.

def task1_recursion(string: str):
    print(string)
    if len(string) > 1:
        if string[0] == task1_recursion(string[1::1]):
            return True
        else:
            return False
    else:
        return string

My code seems to one the last recursion return string “” and that makes it to return False.

Adam Smith Trainee Asked on November 5, 2019 in Python.
Add Comment
1 Answers

Just check the tip and the tail, continue with the string without them:

def task1_recursion(string: str):
    # recursion base condition (exit condition)
    if len(string) <= 1:
        return True
    # unpack values
    first, *_, last = string
    # check if they are different
    if first != last:
        return False
    # if not continue checking the remaining string
    return task1_recursion(string[1:-1])
Reviewer Answered on November 5, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.