Day 15: Palindrome Checker

Objective

Your task today is to create a program that checks if a given word or phrase is a palindrome. A palindrome is a sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization.

For example:

  • Input: "racecar"
  • Output: "True"
  • Input: "A man a plan a canal Panama"
  • Output: "True"

This challenge will help you work with strings, loops, and data cleaning techniques.


Why This Challenge Is Important

This challenge teaches you key programming concepts:

  1. String Manipulation: Learn to modify and analyze strings to extract useful information.
  2. Conditional Logic: Use conditions to determine whether a string is a palindrome.
  3. Data Cleaning: Practice removing unnecessary characters and handling edge cases like capitalization and spaces.

Steps to Solve

1. Understand the Problem

  • A palindrome reads the same backward as forward.
  • Ignore spaces, punctuation, and capitalization when checking for a palindrome.

2. Approaches to Solve

There are two main approaches to solving this problem:

  1. Using Loops: Compare characters at the beginning and end of the string while iterating inward.
  2. Using String Reversal: Clean the string, reverse it, and compare it to the original cleaned string.

3. Clean the Input

  • Remove spaces, punctuation, and other special characters.
  • Convert all characters to lowercase to ignore capitalization.

Code Examples

Python Example

Using Loops:

# Get input from the user
text = input("Enter a word or phrase: ")

# Clean the string: remove spaces, punctuation, and make it lowercase
cleaned_text = "".join(char.lower() for char in text if char.isalnum())

# Check if it's a palindrome using loops
is_palindrome = True
for i in range(len(cleaned_text) // 2):
    if cleaned_text[i] != cleaned_text[-(i + 1)]:
        is_palindrome = False
        break

# Output the result
print("Is it a palindrome?", is_palindrome)

Using String Reversal:

# Get input from the user
text = input("Enter a word or phrase: ")

# Clean the string: remove spaces, punctuation, and make it lowercase
cleaned_text = "".join(char.lower() for char in text if char.isalnum())

# Check if the cleaned string is equal to its reverse
is_palindrome = cleaned_text == cleaned_text[::-1]

# Output the result
print("Is it a palindrome?", is_palindrome)

Java Example

Using Loops:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get input from the user
        System.out.print("Enter a word or phrase: ");
        String text = scanner.nextLine();

        // Clean the string: remove spaces, punctuation, and make it lowercase
        String cleanedText = text.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

        // Check if it's a palindrome using loops
        boolean isPalindrome = true;
        for (int i = 0; i < cleanedText.length() / 2; i++) {
            if (cleanedText.charAt(i) != cleanedText.charAt(cleanedText.length() - 1 - i)) {
                isPalindrome = false;
                break;
            }
        }

        // Output the result
        System.out.println("Is it a palindrome? " + isPalindrome);
    }
}

Using StringBuilder:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Get input from the user
        System.out.print("Enter a word or phrase: ");
        String text = scanner.nextLine();

        // Clean the string: remove spaces, punctuation, and make it lowercase
        String cleanedText = text.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

        // Check if the cleaned string is equal to its reverse
        String reversedText = new StringBuilder(cleanedText).reverse().toString();
        boolean isPalindrome = cleanedText.equals(reversedText);

        // Output the result
        System.out.println("Is it a palindrome? " + isPalindrome);
    }
}

JavaScript Example

Using Loops:

// Get input from the user
let text = prompt("Enter a word or phrase:");

// Clean the string: remove spaces, punctuation, and make it lowercase
let cleanedText = text.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();

// Check if it's a palindrome using loops
let isPalindrome = true;
for (let i = 0; i < cleanedText.length / 2; i++) {
    if (cleanedText[i] !== cleanedText[cleanedText.length - 1 - i]) {
        isPalindrome = false;
        break;
    }
}

console.log("Is it a palindrome?", isPalindrome);

Using String Reversal:

// Get input from the user
let text = prompt("Enter a word or phrase:");

// Clean the string: remove spaces, punctuation, and make it lowercase
let cleanedText = text.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();

// Check if the cleaned string is equal to its reverse
let isPalindrome = cleanedText === cleanedText.split("").reverse().join("");

console.log("Is it a palindrome?", isPalindrome);

Edge Cases to Consider

  1. Empty Input: An empty string should be considered a palindrome.
  2. Single Character: A single character is always a palindrome.
  3. Special Characters and Spaces: Ensure punctuation and spaces are ignored in the check.

Extensions to Explore

  1. Find All Palindromes in a List: Extend the program to find all palindromes in a list of words or phrases.
  2. Longest Palindrome: Write a program to find the longest palindrome in a given text.
  3. Case Sensitivity Toggle: Allow the user to toggle whether the program should ignore capitalization.

What You’ve Learned

  • How to clean and preprocess data before analyzing it.
  • How to manipulate strings using loops and slicing techniques.
  • How to solve problems that require conditional logic and data validation.

Next Steps

In Day 16: Sorting a List, you’ll write a program that sorts a list of numbers in ascending or descending order.