#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    6
    Rep Power
    0

    Beginners difficulty with return


    The following recursive code returns true if string s is a palindrome

    def isPal(s):
    if len(s) <= 1:
    return True
    else:
    return s[0] == s[-1] and isPal(s[1:-1])


    s ='elonole'

    print isPal(s)

    I donít understand why the following code returns none
    (and not true)


    def isPal(s):
    if len(s) <= 1:
    return True
    else:
    if s[0] != s[-1]:
    return False
    else:

    isPal(s[1:-1])


    s ='elonole'

    print isPal(s)

    I would appreciate explanation
    Last edited by SimonWr; May 18th, 2013 at 07:48 AM. Reason: formatting wrong
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    2
    Please post using code tags.

    For your code, you recursively call the function in that else block, but don't return anything (defaulting to returning None). You need to return the result of the recursive call.

    I beleive this is what you wanted:
    python Code:
    def isPal(s):
        if len(s) <= 1:
            return True
        elif s[0] != s[-1]:
            return False
        else:
            return isPal(s[1:-1])
     
     
    s ='elonole'
     
    print isPal(s)

    On another note; why are you checking if it is a palindrome in this fashion? Is it a requirement?

    This does the same thing:
    python Code:
    def ispal(some_string):
        return some_string == some_string[::-1]

    -Mek
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    6
    Rep Power
    0

    Thankyou


    Mek
    Thats really helpful - thank you
    I will try to get to grips with code tags
    it was a bit disappointing to see tabulation disappear when I finished edit.
    I am a 52 year old who did not try programming for the first 50 years.
    I am working through introduction to computation and programming using python by John Guttag.
    Simon

IMN logo majestic logo threadwatch logo seochat tools logo