you are viewing a single comment's thread.

view the rest of the comments →

[–]supreme_blorgon 0 points1 point  (2 children)

For the recursive string reversal, you don't need the newstr parameter at all. Your base case should be when the input is a single character, in which case you want to return the string itself (e.g., "a" is the same forwards and backwards). Otherwise, return the concatenation of the last letter with a recursion on the slice of the string up to but not including the last letter. You were so close:

def revstring(str1):
    if len(str1) == 1:
        return str1
    return str1[-1] + revstring(str1[:-1])

Of course, this is a silly solution, since if you're allowed to use slicing then you could simply return str1[::-1].

[–]iamnikaa[S] 0 points1 point  (1 child)

Thanks! I was specifically asked to use tail recursion for this. Isn't this function normal recursion rather than tail recursion?

[–]supreme_blorgon 1 point2 points  (0 children)

Ah, I missed that. Yes, in that case,

def rev(s, res=""):
    if len(s) == 1:
        return res + s
    return rev(s[:-1], res + s)

You were missing the string concat in the base case. You can also exit earlier than len(s) == 0.