I'm currently studying python from http://www.sololearn.com/Play/Python and I'm having trouble understanding why this code works.
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(1))
I get how recursion works for a fibonacci and factorial but I can't wrap my head around this one.
It's based on an inductive definition of evenness:
"odd" is obviously "not even".
The code takes this definition, and checks it backwards - using recursion.
is_even'
s base case resolves to True
. Since is_odd(x)
returns not is_even(x)
, the value True
will be a part of the expression returned by is_odd
. The question is how many times will that True
value be negated . By tracing the calls you can see it will be negated an even number of times, and hence "retain" its truthiness, when x
is odd [eg: x=3
==> (not (not (not (not True))))
== True
] and an odd number of times, and hence "lose" its truthiness, when x
is even [eg: x=2
==> (not (not (not True)))
== False
]. There's probably some term from logic that names this general property of multiple negation.
That recursive function is really a bad way to teach recursion, you should apply recursion only when it's useful. In fact, test those functions with negative numbers and you'll get RuntimeError: maximum recursion depth exceeded
errors.
To check parity numbers you'd better use %
operator or &
and operator, ie:
def is_even(x):
return (x & 1) == 0
def is_odd(x):
return (x & 1) == 1
That said, I think @Elazar & @DAXaholic answers should give you some insights about that buggy recursive function and wrap your mind about it.
A little hint:
0 -> True
1 -> not True
2 -> not not True
3 -> not not not True
...
and so on.
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.