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


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

Ask a doubt
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.