user1294377
user1294377

Reputation: 1081

Palindrome function not working in Python

the following is part of a much bigger program.

wordStr = open("words.txt",'rU')

def isPalindrome(wordStr):
    palindromeCount = 0
    for word in wordStr:
        if word == word[::-1]:
            palindromeCount += 1
    print palindromeCount

isPalindrome(wordStr)

words.txt contains thousands of words and it is in the same folder as the program. With this function I am trying to go through and count the number of words that are palindromes (spelled the same front and back) in the text file. It simply returns 0 every time and never even gets into the if statement and I can't figure out why.

Upvotes: 2

Views: 255

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61643

sum(word == word[::-1] for word in wordStr.read().split())

Upvotes: 0

K. Brafford
K. Brafford

Reputation: 3859

You need to strip extra newlines from the individual lines and have your function return a value:

wordFile = open("words.txt",'rU')

def PalindromeCount(wordFile):
    palindromeCount = 0
    for word in wordFile:
        word = word.strip()
        if word == word[::-1]:
            palindromeCount += 1
    return palindromeCount

When I run it on this data:

meatloaf
radar
ardra
fish

I get this result: 2

Upvotes: 2

DSM
DSM

Reputation: 353499

for word in wordStr will iterate over the lines in wordStr. Probably each of your lines has an end-of-line marker, something like \n. If you print repr(word), you'll probably see it.

I would try

for word in wordStr:
    print repr(word)
    word = word.strip()
    [etc]

as a first pass.

Upvotes: 4

Related Questions