Reputation: 2159
I am using recursion to reverse a string. I am able to reverse a string successfully using following code.
def rev(string):
if len(string)==0:
return string
if len(string)==1:
return string
else:
s=string
string = s[-1]+rev(s[:-1])
return string
But when i am replacing return with print it is printing only the first two characters of answer and then throwing an error saying
"TypeError: cannot concatenate 'str' and 'NoneType' objects"
Example. when give 'StackOverflow' to function and returned a value it returns 'wolfrevOkcatS' corrrectly but when I am trying to print the answer in the function itself, it is only printing "tS" giving the error above.
Upvotes: 1
Views: 108
Reputation: 2662
I suspect that you did something like this:
def rev(string):
if len(string)==0:
print string
if len(string)==1:
print string
else:
s=string
string = s[-1]+rev(s[:-1])
print string
Let's get right to the problem. Supposed the string you are trying to reverse is abc
. In the first call, you will hit the else clause and try to evaluate:
'c' + rev('ab')
The problem is now that your function has no return statements, rev('ab')
returns None. And python raises an error when you try to concatenate a string with None.
With the return statements. rev('ab') returns 'ba' and the plus sign can be used to concatenate 'c'
with 'ba'
.
As an aside, if you are ever trying to solve this problem in production code, you should be using the built in tools.
reversed_str = myStr[::-1]
reversed_str_iterator = reversed(myStr)
Upvotes: 2
Reputation: 9335
To reverse a string/list
in Python
use list[::-1]
Demo
>>> my_str = 'StackOverflow'
>>> my_str[::-1]
'wolfrevOkcatS'
Upvotes: 1
Reputation: 155363
If you don't return
from a function, then the function implicitly returns None
. By replacing return
with print
, you break the recursive functionality; it recurses, but the values computed in the recursive calls are not returned and used. If you want to print
intermediate results for your own edification, do so, but do so just before each return
statement, not in place of the return
statements.
Upvotes: 1
Reputation: 104712
If you're replacing return
with print
, your function will not return anything. In Python, that is the same as returning None
. This breaks your recursive step where you concatenate the last letter of the string with the return value of the recursive call. Instead, you should just let the recursive call do its own printing (just call it), after print the last letter in a separate statement:
else:
print(s[-1], end="") # or print s[-1], (with the comma!) if you're on Python 2
rev(s[:-1])
Note that you probably want your base cases to print a newline in this situation, since otherwise you won't get one at all.
Upvotes: 1