0

This is my simple code.

def reverseString(aStr):
    newStr = ''
    if len(aStr) == 0:
        return newStr
    else:
        newStr = newStr + aStr[len(aStr)-1]
        return reverseString(aStr[:len(aStr)-1])

For 'alina' (if I insert print newStr before return reverseString...), the output is: newStr='a', newStr='n', newStr='i', newStr='l', newStr='a', newStr=''. I don't get it. Why does it behave like this?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Cathleen
  • 21
  • 2

4 Answers4

3

The reason your function has not worked is because you forgot to return newStr at the end. And every time you call your function, newStr will just get reset back to ''.

There's an easier way to do what you are doing. Use slicing:

def reverseString(s):
    return s[::-1]

Examples:

>>> reverseString('alina')
'anila'

>>> reverseString('racecar')
'racecar' # See what I did there ;)
TerryA
  • 58,805
  • 11
  • 114
  • 143
0

Something like this:

def reverseString(aStr, newStr = ''):
    if len(aStr) == 0:
        return newStr
    else:
        newStr = newStr + aStr[-1]  #-1 returns the last element from the string
        return reverseString(aStr[:-1], newStr) #slice the string up to second last char
print reverseString("foobar")     
#raboof

The problem with your code is that newStr is getting re-assigned at each recursive loop to an empty string(''), you must pass the newStr value in every recursive call.

def reverseString(aStr, newStr= ''): #define a default value for newStr

    if len(aStr) == 0:
        return newStr
    else:
        newStr = newStr + aStr[len(aStr)-1]  #better use aStr[-1]
        return reverseString(aStr[:len(aStr)-1], newStr) #pass the new value of newStr

print reverseString("foobar")# No value is passed for newStr. So, default is used . 
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
-1

You are returning the result of the recursive call, without keeping the information from previous calls. You have this line:

newStr = newStr + aStr[len(aStr)-1]

but newStr is then discarded.

Possible solution:

def reverseString(aStr):
    if len(aStr) == 0:
        return ''
    else:
        return aStr[-1] + reverseString(aStr[:-1])

or simply

def reverseString(s):
    return s[-1]+reverseString(s[:-1]) if s else ''

Note that both these solutions are elegant, but are "normal" recursion, and therefore suboptimal; for a tail-recursive solution (which potentially can be optimized into a loop) see @Ashwini Chaudhary's answer.

Elazar
  • 20,415
  • 4
  • 46
  • 67
-1

Just sayin', there's an easier way to do this, which avoids recursion and the problems that it entails :

>>> ''.join(reversed("abcd"))
'dcba'
michaelmeyer
  • 7,985
  • 7
  • 30
  • 36
  • just saying, this is the 6th time this solution is being suggested here. This is a comment, not an answer, and one that has been suggested already. – Elazar Jun 10 '13 at 11:59
  • Yes, but I am a vet trying to learn programming so I have to understand things first... :) – Cathleen Jun 10 '13 at 12:01
  • @Elazar: I don't see this method mentioned in this page, except in my answer. – michaelmeyer Jun 10 '13 at 12:12
  • See zmo's and Schorsch's comments. – Elazar Jun 10 '13 at 12:28
  • 1
    @doukremt There are two deleted answers that you cannot see which suggested that already; one of the users who wrote those answers added a comment to the question. – apaderno Jun 10 '13 at 12:48