Программа Python Palindrome: проверьте, является ли строка палиндромом

Вот пример программы на Python, которая проверяет, является ли данная строка палиндромом или нет. Палиндром – это слово, фраза, число или другая последовательность символов, которая одинаково читается как в прямом, так и в обратном направлении.

Метод 1: использование разрезания строк

def is_palindrome(s):
    # Remove spaces and convert to lowercase
    s = s.replace(" ", "").lower()

    # Reverse the string using slicing
    reversed_s = s[::-1]

    # Check if the original string and the reversed string are equal
    if s == reversed_s:
        return True
    else:
        return False
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
    print("Palindrome")
else:
    print("Not a palindrome")

Метод 2. Использование цикла

def is_palindrome(s):
    # Remove spaces and convert to lowercase
    s = s.replace(" ", "").lower()

    # Initialize two pointers
    start = 0
    end = len(s) - 1

    # Compare characters from both ends
    while start < end:
        if s[start] != s[end]:
            return False
        start += 1
        end -= 1

    return True
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
    print("Palindrome")
else:
    print("Not a palindrome")

Метод 3. Использование рекурсии

def is_palindrome(s):
    # Remove spaces and convert to lowercase
    s = s.replace(" ", "").lower()

    # Base case
    if len(s) <= 1:
        return True

    # Recursive case
    if s[0] == s[-1]:
        return is_palindrome(s[1:-1])
    else:
        return False
# Test the function
input_string = input("Enter a string: ")
if is_palindrome(input_string):
    print("Palindrome")
else:
    print("Not a palindrome")