简体   繁体   中英

How to check if string1 is the reverse of string2 using recursion (python)

I know how to reverse a string using recursion

def reverse(s):
    if len(s) == 0:
        return s
    return s[-1] + reverse(s[0 : -1])

def main() :
    r = reverse("Hello!")
    print(r)
    print("Expected: !olleH")
main()

However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far:

def isReversed(str1, str2):
    if len(str1) != len(str2):
        return False

I'm not sure how to call the function within itself using two arguments.

Since your reverse() function is good, you could compare string str1 to see if it's the reverse of str2 by:

def isReversed(str1, str2):
    return str1 == reverse(str2)

Because, if str1 and str2 are really the reverse of one another, reversing one of them should make them match.

If you really want to ignore case, then:

def isReversed(str1, str2):
    return str1.lower() == reverse(str2).lower()

You can also do an easy string reversal with str1[::-1] so you could check if str1 == str2[::-1]

If both strings are empty, they are clearly mirror images. Otherwise, compare first and last letters and recurse on the rest of the characters.

def helper(s1, s2):
    if s1 == "" == s2:  # short for s1 == "" and s2 == ""
        return True
    else:
        return s1[0] == s2[-1] and mirror_images(s1[1:], s2[:-1])

The above assumes the strings have the same length; it's best to check that once before you start the recursion:

def mirror_image(s1, s2):
    return len(s1) == len(s2) and helper(s1, s2)
>>> qq = 'xyz'
>>> ww = 'zyx'
>>> qq == ww
 False
>>> ww[::-1]
 'xyz'
>>> qq == ww[::-1]
 True

use can use lower() to take care of the case here is a fuller solution:

In [130]: def rev(x, y):
     ...:     if x == '' and y == '':
     ...:         return True
     ...:     elif x == '' or y == '':
     ...:         return False
     ...:     elif x[0].lower() != y[-1].lower():
     ...:         return False
     ...:     else:
     ...:         return rev(x[1:], y[:-1])
     ...:     
     ...:         
In [131]: rev('abc', 'cba')
Out[131]: True
In [132]: rev('abc', 'cb')
Out[132]: False
In [133]: rev('abc', '')
Out[133]: False
In [134]: rev('', '')
Out[134]: True 

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