python - Recursive Program: What am I doing wrong? -
i trying write code analyze if word palindrome. btw palindrome word read same backward , forward. example "madam" or "noon"
here try:
x = raw_input("please enter word:\n") l = len(x) # part returns first letter of word def first(word): return word[0] # part returns last letter of word def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(word): if l <= 2: print 'enter word @ least 3 letters' elif first(word) != last(word): print 'this word not palindrome' else: word = middle(word) is_palindrome(word) is_palindrome(x)
but when executed,
indexerror: string index out of range ...line 7, in first return word[0]
the first branch of "is_palindrome" works perfectly. i.e. when word not palindrome, no errors. "noopn" executed no errors, error in second branch
i've playing code many times can't figure out "iterative part" have answer don't want @ yet. need figure out 2 things: 1. way make iteration in function is_palindrome work correctly? , 2. way exit program in end.
could folks direct me how answer these questions without providing solution yet?
finally should put print statement: print 'this word palindrome'
thank you
personally, prefer separating check , output. is_palindrome()
should return answer , not responsible telling user. makes more reusable.
def is_palindrome(word): # handle base case if len(word) <= 1: return true elif first(word) != last(word): return false else: word = middle(word) return is_palindrome(word)
this enables do
x = raw_input("please enter word:\n") l = len(x) if l <= 2: print 'enter word @ least 3 letters' elif is_plaindrome(word): print 'this word palindrome' else: print 'this word not palindrome'
this puts validity check front of execution, while in recursion, have checks valid on recursion.
(i doubt if check necessary @ - y
, oo
no palindromes? argue empty string, however...)
the next improvement steps omit functions first()
, last()
, middle()
- trivial , used once, put there code used.
Comments
Post a Comment