I have a question related to change in program behavior the absence of return statement leads to in a python method.
The count method below prints number of digits in a given integer. With the below chunk of code I get the result as 4, which is the expected result.
def count(x,acc=0):
if x==0:
return acc
return count(x/10,acc+1)
print "Count is %s" %(count(1234))
Result: Count is 4
If I modify the above method so that the last statement does not contain the 'return' statement the result I get is 'None'.
def count(x,acc=0):
if x==0:
return acc
count(x/10,acc+1)
print "Count is %s" %(count(1234))
Result: Count is None
(The version of Python I used is: 2.7.3)
Does the above behavior results due to the fact that Python doesn't do tail call optimization or is there any other reasoning involved ?
A similar chunk of code in perl (which AFAIK doesn't do tail call optimization) provides the expected result without 'return' being part of the last statement.
sub counter {
my ($n,$acc) = @_;
return $acc if ($n==0);
counter(int($n/10), $acc+1);
}
print "Count is:" . counter(1234,0) ."\n"
Result: Count is:4
(The versions of Perl I ran above code chunk are : 5.14.4 and 5.8.5).
My questions are:
- Is Tail Call optimization the reason for the behavior shown in above chunk of Python code.
- If that were the case then why behavior of perl code differs, which doesn't do TCO either.