Wednesday, 7 August 2013

Iterative Program: What am I doing wrong?

Iterative Program: What am I doing wrong?

I am trying to write a code that would analyze if a word is a palindrome.
BTW a palindrome is a word that is read the same backward and forward.
Example are "madam" or "noon"
Here is a try:
x = raw_input("please enter a word:\n")
L = len(x)
# this part returns the first letter of the word
def first(word):
return word[0]
# this part returns the last letter of the word
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if L <= 2:
print 'enter a word with at least three letters'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
is_palindrome(word)
is_palindrome(x)
But when executed, I get
IndexError: string index out of range
...line 7, in first return word[0]
The first branch of "is_palindrome" works perfectly. i.e. when the word is
not a palindrome, I get no errors. Like "noopn" is executed with no
errors, but the error is in the second branch
I've playing with this code for so many times but can't figure out the
"iterative part" I have the answer but I don't want to look at it yet. I
need to figure out two things: 1. a way to make the iteration in the
function is_palindrome work correctly? and 2. a way to exit the program in
the end.
Could you folks direct me to how to answer these questions without
providing the solution yet?
Finally where should I put the print statement: print 'This word is a
palindrome'
Thank you

No comments:

Post a Comment