Palindrome program in python using file i/o -


i new python , working on few programs hang of it. making palindrome program takes input file , prints out words palindromes. here code have far

def ispalindrome(word):     if len(word) < 1:         return true     else:         if word[0] == word[-1]:             return ispalindrome(word[1:-1])         else:             return false  def fileinput(filename):     file = open(filename,'r')     filecontent = file.readlines()     if(ispalindrome(filecontent)):         print(filecontent)     else:         print("no palindromes found")     file.close() 

this file

moom mam madam dog cat bat 

i output of no palindromes found.

the contents of file read in list, filecontent end as:

filecontent = file.readlines() filecontent => ["moon\n", "mam\n", "madam\n", "dog\n", "cat\n", "bat\n"] 

you fix by:

def fileinput(filename):     palindromes = false     line in open(filename):         if ispalindrome(line.strip()):              palindromes = true              print(line.strip(), " palindrome.")      return "palindromes found in {}".format(filename) if palindromes else "no palindromes found." 

note: have added palindromes flag purposes of returning final "palindromes [not] found" statement


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -