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

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    A quick easy one


    Nevermind ... I'll leave the question for a chuckle. However, it's because 'is_palindrome' should have a Return in front of it.
    Silly code, just doing as it was told to.

    Can someone please explain this insanity to me.

    Code:
    def is_palindrome(s):
        print len(s)
        if len(s) == 0:
            print 'i was called'
            return True
        if s[0:1] == s[(len(s)-1):len(s)]:
                is_palindrome(s[1:len(s)-1])
        else:
            return False
    print is_palindrome('abba')

    Results:
    4
    2
    0
    i was called
    None

    I know, I know, your thinking . . . . well of course this should return True. However, you must remember this is programming a lot of times things just don't make sense. So in this case instead of returning True it ignores that and decides it's going to go with None.

    But why?

    And you get a gold star if you can tell me how you would code it so when it gets to line that says "Return True" it ......
    wait for it.

    Returns True.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,709
    Rep Power
    480
    # Recursion is a poor idea
    # testing is a good idea.
    # this program is non-recursive and untested.
    # you decide.

    def is_palindrome(s):
    L = list(s)
    return L == list(reversed(L))
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    588
    Rep Power
    64
    Tested and very simple ...
    Code:
    def is_palindrome(s):
        return s == s[::-1]
    
    print(is_palindrome('racecar'))  # True
    Improvements can be lower case and letters only.

    Comments on this post

    • b49P23TIvg agrees : Surprise! I thought that would fail for is_palindrome([1,2,3,2,1])# succeeds!
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo