68.9k views
2 votes
A palindrome is a word or sequence of characters which reads the same backward and forward, such as madam, dad, racecar, 5885. Write a class "Palindrome" that takes a word as input and returns if the word is palindrome or not; implement a driver program that asks users to enter 5 words; and prints the list of palindrome and not palindrome words. If user input is: dad, 123, mom, xyz, racecar The output will be: Palindrome: dad, mom, racecar Not palindrome; 123, xyz

1 Answer

7 votes

Answer:

  1. class Palindrome:
  2. def __init__(self, word):
  3. self.word = word
  4. self.status = self.checkPalindrome(word)
  5. def checkPalindrome(self, word):
  6. for i in range(0, len(word)//2):
  7. if(word[i] != word[len(word) - 1 - i]):
  8. return False
  9. return True
  10. words = input("Input five words: ")
  11. word_list = words.split(" ")
  12. p_list = []
  13. np_list = []
  14. for w in word_list:
  15. p = Palindrome(w)
  16. if(p.status):
  17. p_list.append(p.word)
  18. else:
  19. np_list.append(p.word)
  20. print("Palindrome: " + " ".join(p_list))
  21. print("Not palindrome: " + " ".join(np_list))

Step-by-step explanation:

Firstly create a Palindrome class with one constructor that will take one input word (Line 1-2). There is a checkPalindrome method in the class to check if the input word is a palindrome (Line 6-10). If so, return True and set the boolean value to status instance variable (Line 4) or False it is not a palindrome.

In the main program, we ask user to input five words and split them into a list of individual words (Line 12 -13). Use a for loop to traverse through each word from the word_list and create a Palindrome object (Line 17 -19). When a Palindrome object is created, it will automatically call the checkPalindrome method and set the status either true or false. If the object status is true, add the word of current Palindrome object to p_list otherwise add it to np_list (Line 19-22).

Lastly, display the list of palindrome and non-palindrome (Line 24-25).

User Pavel Zagalsky
by
5.6k points