Q.Program 8-5: Write a program using a user defined function to check if a string is a palindrome or not. (A string is called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →A palindrome reads the same both ways, so compare the first character with the last, the second with the second-last, moving inwards — the first mismatch proves it is not a palindrome; if the pointers cross with no mismatch, it is. Case-fold first so "Kanak" qualifies.
Idea. Rather than building the reversed string and comparing, the classic two-pointer method checks the defining property directly: st[0] must equal st[-1], st[1] must equal st[-2], and so on. Two index variables i (front) and j (rear) walk toward each other. Since the book counts "Kanak" as a palindrome, we convert the input to lowercase before checking — otherwise 'K' vs 'k' would fail.
def checkPalindrome(st):
"""Return True if st is a palindrome, else False."""
i = 0
j = len(st) - 1
while i < j:
if st[i] != st[j]:
return False # a mismatch settles it immediately
i += 1
j -= 1
return True # pointers met/crossed: all pairs matched
# main program
st = input("Enter a string: ")
st = st.lower() # treat 'K' and 'k' as the same letter
if checkPalindrome(st):
print("The given string", st, "is a palindrome")
else:
print("The given string", st, "is not a palindrome")
Trace for st = "kanak" (indices 0–4):
| Step | i | j | st[i] | st[j] | Match? |
|---|---|---|---|---|---|
| 1 | 0 | 4 | k | k | yes → move in |
| 2 | 1 | 3 | a | a | yes → move in |
| 3 | 2 | 2 | — | — | i < j is False → loop ends |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.