String mirror equality

... by Bittle in Programming Help January 12, 2021


Write a boolean recursive function receive two strings and checks if one is reflection of the other


Strings are one mirror of the other:

"abcd" "dcba"

"$" "$"

"" "" (empty string)

Strings are not mirror one to the other:

"axcd" "dcba"

Write main function to check the strings to the output

("Reverse" must not be used)


# recursive function to check if a == reflection of b
# abcd == dcba
# ascd != asrc
def is_mirror(a, b):
    if len(a) != len(b):
        # both strings must be the same length
        return False

    if a == "":
        # both string are empty, return true
        return True

    if a[0] == b[-1]:
        # first char of a == last char of b
        return is_reflection(a[1:], b[:-1])  # remove the first char of a, and remove the last char of b
        return False

if __name__ == '__main__':
    str1 = "dcba"
    str2 = "abcd"
    if is_mirror(str1, str2):
        print(str1 + " is a mirror of " + str2)
        print(str1 + " is not a mirror of " + str2)

Comments (0)

Search Here