Check Palindrome šŸŽÆ

beginner
14 min

Check Palindrome šŸŽÆ

Welcome to our deep dive into the fascinating world of Palindromes! In this lesson, we'll learn how to write a program that checks if a given string is a palindrome. We'll start from the basics and gradually move towards more advanced concepts. Let's get started!

What's a Palindrome? šŸ“

A palindrome is a word, phrase, number, or any sequence of characters that reads the same forward and backward. For example, "racecar", "level", "12321", and "A man, a plan, a canal: Panama" are all palindromes.

Why Check for Palindromes? šŸ’”

Checking for palindromes is a fundamental concept in programming, especially in string manipulation. It's a great way to understand how to iterate through strings, compare characters, and handle edge cases. Plus, it's a fun problem to solve!

Checking for Palindromes: Simple Approach šŸ“

Let's start with a simple approach to check if a string is a palindrome. We'll compare each character in the string with its reverse counterpart. If they match, the string is a palindrome.

python
def is_palindrome(s): s = s.lower() # Ensure case insensitivity reversed_s = s[::-1] # Reverse the string if s == reversed_s: return True else: return False

šŸ’” Pro Tip: Notice we're using the lower() function to make our palindrome check case-insensitive.

Checking for Palindromes: Efficient Approach šŸ’”

The simple approach we saw earlier is straightforward but not very efficient, especially for long strings. In the efficient approach, we'll compare the first and last characters, then move towards the center, comparing each character pair until we reach the middle.

python
def is_palindrome(s): s = s.lower() length = len(s) for i in range(length // 2): if s[i] != s[length - i - 1]: return False return True

šŸ’” Pro Tip: This approach is more efficient because it only needs to iterate half of the string and stops as soon as it finds a mismatch.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

What does the function `is_palindrome(s)` return if `s` is the string "racecar"?

Summary šŸ“

In this lesson, we learned what a palindrome is and why it's important to check for palindromes in programming. We wrote two functions to check if a given string is a palindrome: a simple approach and an efficient approach. We also took a quiz to test our understanding. Happy coding! šŸŽ‰