简体   繁体   中英

How to write this iterative function to be recursive?

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.

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])

If I understand correctly you want to check if a string is symmetric with the code in task1 . My solution is below:

def fct(s: str, i: int):
    if len(s) <= 1 or i == len(s):
        return True
    return s[i] == s[len(s) - 1 - i] and fct(s, i + 1)

I tested and fct produces the same result as task1 . It needs an additional parameter for the index though. But you can wrap it inside another function if you want the parameter to include only the input string. i is always set to 0 when you call the function, eg fct("ABCCBA", 0) .

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