Recursive function in python does not call itself out
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Recursive Function In Python Does Not Call Itself Out
01:04 Answer 1 Score 6
01:29 Accepted Answer Score 1
02:18 Answer 3 Score 1
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/5401...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python27
#avk47
ANSWER 1
Score 6
This is a much simplified recursive version that actually uses the single char comparison to reduce the problem size:
def rhs(s):
    half, rest = divmod(len(s), 2)
    if rest:  # odd length
        raise ValueError  # return 'error'
    if half == 0:  # simplest base case: empty string
        return True
    return s[0] == s[half] and rhs(s[1:half] + s[half+1:])
It has to be said though that, algorithmically, this problem does not lend itself well to a recursive approach, given the constraints.
ACCEPTED ANSWER
Score 1
Here is another recursive solution. A good rule of thumb when taking a recursive approach is to first think about your base case.
def recursiveHalfString(s):
    # base case, if string is empty
    if s == '':
        return True
    if (len(s))%2==0:
        if s[0] != s[(len(s)/2)]:
            return False
        else:
            left = s[1:len(s)/2]  # the left half of the string without first char
            right = s[(len(s)/2)+1: len(s)] # the right half without first char
            return recursiveHalfString(left + right)
    else:
        return "Error: odd string"
print(recursiveHalfString('abbaabba'))   # True
print(recursiveHalfString('fail'))       # False
print(recursiveHalfString('oddstring'))  # Error: odd string
This function will split the string into two halves, compare the first characters and recursively call itself with the two halves concatenated together without the leading characters.
However like stated in another answer, recursion is not necessarily an efficient solution in this case. This approach creates a lot of new strings and is in no way an optimal way to do this. It is for demonstration purposes only.
ANSWER 3
Score 1
Another recursive solution that doesn't involve creating a bunch of new strings might look like:
def recursiveHalfString(s, offset=0):
    half, odd = divmod(len(s), 2)
    assert(not odd)
    if not s or offset > half:
        return True
    if s[offset] != s[half + offset]:
        return False
    return recursiveHalfString(s, offset + 1)
However, as @schwobaseggl suggested, a recursive approach here is a bit clunkier than a simple iterative approach:
def recursiveHalfString(s, offset=0):
    half, odd = divmod(len(s), 2)
    assert(not odd)
    for offset in range(half):
        if s[offset] != s[half + offset]:
            return False
    return True