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)
The 'int' and 'NoneType' can not be added through + operation.
Here is my console for running your very last code:
line 13, in collatz_recursive
return 1 + collatz(n * 3 + 1)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
I think the problem is that you forgot to handle the edge-case n=1 for your collatz_recursive
function, you can easily log n
by putting a print function before and after while loop and observe the bug.
Try to return a default value for your function, this is also named base-case
. You can read more about recursion and base case in here
"Python gives me an error when ... I reference the same function within itself"
No, Python gives you an error because collatz_recursive
doesn't return a value for n == 1
. The return value of a function is None
if no value was returned with a return
statement.
Your Python code should look like
def collatz_recursive(n):
if n == 1:
return 0
if n % 2 == 0:
return 1 + collatz_recursive(n/2)
else:
return 1 + collatz_recursive(n * 3 + 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.