Hello,

I am knew here and not sure how to ask but I guess I will ask it here and if this is not where it goes feel free to tell me where to post it.....THANKS

I am trying to write a recursive function Python program that will ask the user to input a phrase. It is to remove the first or last character if it is puncutation and then tell the user if their phrase is a palindrome or not.

I am not sure even where to begin....I would I assume that we would prompt the user with:
phrase = raw_input("Enter a phrase: ")
then try to compare the first letter to the last letter and see if they are the same, if they are then the entire string is a palindrome if everything between those letters is a palindrome. But as I stated earlier we have to exclude the punctuation (not sure how).
I would also assume that we would need to put everything into lowercase with somthing like string.lower(phrase) MAYBE??

I am certainly not trying to get a freebie for homework but not too sure in what order to put the steps and the correct python coding for everything.

THANKS---Steve

Recommended Answers

All 14 Replies

Here is what I have come up with so far:

def isPalindrome():

phrase = raw_input("Enter a phrase: ")
phrase_letters = [c for c in phrase.lower() if c.isalpha()]

if phrase_letters[0] != phrase_letters[:-1]:
print phrase + " is not a palindrome."

else:
print phrase + " is a palindrome."

isPalindrome()

Ok, so your trying to see if a word is a palindrome or not?

I notice that in your code you only compare the first and last letter. But really, a palindrome is a word whose letters are in the same order, forward and backward.

First lets plan this out.

We know that if the word is a palindrome, its the same forward and backward. So first:

1) If the word has punctuation, we remove it. (Sorry but I have no idea how to do this one xD)
2) Print the word backward
3) Check to see if the new backward word and the original are the same

The code would look something like this:

def isPalindrome(phrase):
    """Find out if the word is a palindrome or not."""
    
    #This string will be filled in to make the word backward
    backward = ""

    word = str(word)
    word = word.lower()

    #Now lets make the word backward
    for letter in word:
        backward = letter + backward

    #Now lets see if they are the same
    if word == backward:
        rep = word + " is a palindrome!"
    else:
        rep = word + " is not a palindrome!"
    
    return rep

#Actual program now

phrase = raw_input("Enter a word or phrase: ")
isPalindrome(phrase)

Does this help you? Sorry that I can't figure out how to replace punctuation!

Here is the file that I sent to the professor as my draft:

import string

def is_palindrome():

s = raw_input("Please enter a phrase: ")
s = string.replace(s, " ", "")
s = string.lower(s)
print s

i = 0
is_palindrome = True

while i < len(s)/2:
if s != s[-1-i]:
is_palindrome = False
break
i = i + 1

if is_palindrome:
print "Your phrase is a palindrome"
else:
print "Your phrase is not a palindrome."

is_palindrome()


and here was his response:

try this also:
# if s[0] != s[-1]:
if s != s[-i - 1]:

But, you're supposed to be solving this problem recursively, and
instead you're doing it iteratively! Don't think about changing
the value of i, but rather of
-- what is the simplest palindrome? (an empty string)
-- a one-character string is also a palindrome.
-- if it's not that simple, then what?
-- if the first and last characters are the same,
then the substring which consists of all but those two characters
must be a palindrome.

.....My program seems to do a decent job but I am a bit confused with how to make the recursion part of the program.....Any help would be most appreciated.

Sorry, but Im a bit confused on the definition of 'recursive'.

The dictionary.com definition:

1) The process of defining a function or calculating a number by the repeated application of an algorithm.

2) When a function (or procedure) calls itself. Such a function is called "recursive". If the call is via one or more other functions then this group of functions are called "mutually recursive".

I guess what he wants is to have the actual program (the stuff that the user sees on the screen) outside of the function, but all of the word processing stuff that the computer does in the function.

But if you could tell me what 'recursive' means, I can help you.

I'm not real sure either but perhaps something more on the line of (forgive the clumsiness of the code. I'm in a hurry)

def is_palindrome(string_in):
   if string_in[0] == string_in[-1]:
      return True, string_in[1:-1]
   return False, string_in

##----------------------------------------------------------
if __name__ == "__main__":
   s = raw_input("Enter palindrome string ")
   orig_s = s
   ok=1
   while s:
      result, s = is_palindrome( s )
      if not result:
         print orig_s, "is NOT a palindrome"
         s=""
         ok=0
   if ok:
      print orig_s, "is a palindrome"

Here is a couple of examples out of the text:

# Recursive definition that translates a factorial into code

def fact():
if n == 0:
return 1
else:
return n * fact(n-1)

# Recursive definition of reversing a word/string

def reverse(s):
if s == "":
return s
else return reverse(s[1:]) + s[0]

and in the book it is noted that to build a correct recursive function we need a base case for which no recusion is required, otherwise the recursion is circular. I know it seems like it should be pretty simple but I can not seem to figure it out.

Here's what your prof meant:

let s = "refer"

then s[0] == s[-1], so we check

s = "efe"

and s[0] == s[-1], so we check

s = "f"

and s[0] == s[-1], so we check

""

which is empty, so we're done, and we return True.

So what you need to do is to come up with code to carry out the process above.

Basically, coding recursion comes down to:

* What is the base case? ("" should return True)
* What is the recursion invariant? (s[0] == s[-1] means keep testing; s[0] != s[-1] means return False).

And then you code it.

Jeff

so how/what would I need to change in my program to get it to ignore what it has checked already assuming the first letter and last letter match? Should I get rid of the part that says

while i < len(s)/2:
if s != s[-1-i]:
is_palindrome = False
break
i = i + 1

I am assuming that the first part would be something like

if s == "":
return "This is a palindrome"
else:
?????? this is the part I can not figure out

Another way is if you keep

s[0] == s[-1]

But each time, if that statement is true, you can remove the first and last letters.

I modified the earlier code for recursion. I do not like recursion and don't use it. A loop is easier to debug and understand. Unless you are specifically told that you have to use recursion, don't. Basically, the function calls itself until the length of the string is zero, or the condition is false. It then returns True or False. The print statement shows each recursion. There has to be a more elegant way to do this but I don't use recursion and haven't tested this code beyond a few simple examples.

def is_palindrome(string_in):
   if (string_in): 
      if (string_in[0] == string_in[-1]):
         result = is_palindrome(string_in[1:-1])
         print string_in, "is palindrome"
         if result:
            return True
   else:
      return True    ## no more letters
   return False

##----------------------------------------------------------
if __name__ == "__main__":
   s = raw_input("Enter palindrome string ")
   result = is_palindrome( s )
   print "The final result is", s,
   if not result:
      print "is NOT a palindrome"
   else:
      print "is a palindrome"

Thanks to everyone for all of your help on the palindrome program the only thing I changed in regards to the program is the fact we may need to lower case the phrase and get rid of the spaces in a sentence. I still can not figure out how to get rid of punctuation short of replacing every piece of punctuation with a "". Here is what I came up with including the few changes:

import string

def is_palindrome(phrase):
if (phrase):
if phrase[0] == phrase[-1]:
result = is_palindrome(phrase[1:-1])
print phrase, "is palindrome"
if result:
return True
else:
return True ## no more letters
return False

if __name__ == "__main__":

s = raw_input("Enter string to be checked: ")
s = string.lower(s)
s = string.replace(s, " ", "")

result = is_palindrome(s)
print "The result is that", s,
if not result:
print "is NOT a palindrome"
else:
print "is a palindrome"

I still can not figure out how to get rid of punctuation

One of the earlier posts already mentioned this.

s = raw_input("Enter string to be checked: ")
s = s.lower()     ## don't use string as it is deprecated
s_ltrs_only = ""
for each_char in s:
   if (each_char >= "a") and (each_char <= "z"):   
      s_ltrs_only += each_char
print s, s_ltrs_only

if (each_char >= "a") and (each_char <= "z"):

OR

if isalpha(each_char):

how to check a number whether is a palindrome or not through recursion function......
suppose i enterred a number 56765
n i have to check its palindromic nature....how should i write a recrsive fuction for checking it....what should be my base statement?
kindly help me finding the solution

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.