It seems as if C allows for a function to reference itself (in a recursive manner) when executing, for example, the Collatz conjecture.
int collatz(int n);
int main(void)
{
int result = collatz(9);
printf("Steps: %i\n", result);
}
int collatz(int n)
{
if (n == 1)
return 0;
else if ((n % 2) == 0)
return 1 + collatz(n / 2);
else
return 1 + collatz(3 * n + 1);
}
Python gives me an error when I try this:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
when I reference the same function within itself:
def collatz_recursive(n):
while n != 1:
if n % 2 == 0:
return 1 + collatz_recursive(n/2)
else:
return 1 + collatz_recursive(n * 3 + 1)
However, when I place collatz in its own function and reference it from the outside with collatz_recursive I don't have that problem:
def collatz(n):
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = n * 3 + 1
def collatz_recursive(n):
while n != 1:
if n % 2 == 0:
return 1 + collatz(n/2)
else:
return 1 + collatz(n * 3 + 1)
whileat all? Your Python code fails not because of any Python language limitation, but because you messed up porting your code.if n == 1part of the C functioncollatz_recursivesometimes returns None.