Write a Python program to check if a string is a palindrome or not.

 

Answer:

A palindrome is a sequence of characters that read the same backwards as forwards. 

Example: level, madam, refer, etc.

To check if a string is palindrome:

  • First, insert all characters of the string into a stack. 
  • Then, using a for loop, keep popping the elements of the stack and compare them with corresponding characters of the string from the beginning. 
  • If at any point, there is a mismatch, then the string is not a palindrome.

Code:

def push(stack,x):

stack.append(x)

return

def pop_stack(stack):

if len(stack)==0:

return

else:

c=stack.pop()

return c

def compare(string,stack):

for i in range(len(string)):

if string[i]!= pop_stack(stack):

return False

return True

stack=[]

input_string=input("Enter a string: ")

for a in input_string:

push(stack,a)

cmp=compare(input_string,stack)

if cmp:

print("Entered string is a palindrome")

else:

print("Entered string is not a palindrome")

 

Output:

Enter a string: madam

Entered string is a palindrome

Slide24.JPG

Remove Ads

Transcript

Write a Python program to check if a string is a palindrome or not. Answer: A palindrome is a sequence of characters that read the same backwards as forwards. Example: level, madam, refer, etc. To check if a string is palindrome: First, insert all characters of the string into a stack. Then, using a for loop, keep popping the elements of the stack and compare them with corresponding characters of the string from the beginning. If at any point, there is a mismatch, then the string is not a palindrome. Code: def push(stack,x): stack.append(x) return def pop_stack(stack): if len(stack)==0: return else: c=stack.pop() return c def compare(string,stack): for i in range(len(string)): if string[i]!= pop_stack(stack): return False return True stack=[] input_string=input("Enter a string: ") for a in input_string: push(stack,a) cmp=compare(input_string,stack) if cmp: print("Entered string is a palindrome") else: print("Entered string is not a palindrome") Output: Enter a string: madam Entered string is a palindrome

Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.