Palindrome Checking - (hw5_part5.py) (8 points) Write a program that has two functions: check_palindrome will take a string argument and return True if it is a palindrome, and False if not. Remember that a palindrome is a string which is the same forwards and backwards. Make sure to convert it all to lowercase with s.lower() because we'll count Racecar and rAcEcaR as palindromes. load_words which will take a file name argument and return a list of words. The words will all be on separate lines, but make sure to strip each line so that the '\n' character is removed.

Respuesta :

Answer:

name = input("Enter the name of file: ")

f = open(name, "r")

for line in f.readlines():

  foundPalindrome = True

  line = line.strip()

  line = line.lower()

  i=0

  for j in range(len(line)-1,-1,-1):

      if i>= j:

          break

      if line[i] != line[j]:

          foundPalindrome = False

          break

      i+=1

  if foundPalindrome:

      print(line," is a Palindrome")

  else:

      print(line," is a not Palindrome")

Explanation:

  • Get the name of file from user and open it in read mode using the built-in open function.
  • Loop through the file to read the lines and set the boolean foundPalindrome to true.
  • Trim the string  and convert it to lower case alphabets.
  • Loop input from last to start  and break out of the loop if i is greater than or equal to j variable.
  • Set the boolean foundPalindrome to false if characters does not match.
  • Finally display that the word is a Palindrome if the boolean foundPalindrome is true otherwise display that word is not a Palindrome.