+ 1
Please explain
can please someone explain 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(17)) print(is_even(23))
5 Answers
+ 13
Don't you just love how recursion works?
+ 12
(cont)
not not not not not not not not not not not not not is_odd(4)
not not not not not not not not not not not not not not is_even(4)
not not not not not not not not not not not not not not is_odd(3)
not not not not not not not not not not not not not not not is_even(3)
not not not not not not not not not not not not not not not is_odd(2)
not not not not not not not not not not not not not not not not is_even(2)
not not not not not not not not not not not not not not not not is_odd(1)
not not not not not not not not not not not not not not not not not is_even(1)
not not not not not not not not not not not not not not not not not is_odd(0)
not not not not not not not not not not not not not not not not not not is_even(0)
not not not not not not not not not not not not not not not not not not True
True
+ 10
Handtrace it.
is_odd(17)
not is_even(17)
not is odd(16)
not not is_even(16)
not not is_odd(15)
not not not is_even(15)
not not not is odd(14)
not not not not is_even(14)
not not not not is_odd(13)
not not not not not is_even(13)
not not not not not is_odd(12)
not not not not not not is_even(12)
not not not not not not is_odd(11)
not not not not not not not is_even(11)
not not not not not not not is_odd(10)
not not not not not not not not is_even(10)
not not not not not not not not is_odd(9)
not not not not not not not not not is_even(9)
not not not not not not not not not is_odd(8)
not not not not not not not not not not is_even(8)
not not not not not not not not not not is_odd(7)
not not not not not not not not not not not is_even(7)
not not not not not not not not not not not is_odd(6)
not not not not not not not not not not not not is_even(6)
not not not not not not not not not not not not is_odd(5)
not not not not not not not not not not not not not is_even(5)
+ 6
Rei Remarkable resilience đ
I'm not the asker, fortunately đ
+ 1
So imagine k to be an even number. When you do is_even(k), it will be is_odd(k - 1) and that's going to be not is_even(k - 1) which is not is_odd(k - 2), that being not not is_even(k - 2) and that's just is_even(k - 2).
So if you keep on doing that you will eventually reach is_even(0) which yields True, because you can take an integer amount of 2 out of k since it's even and that's what even numbers do.
This time, take k to be odd. Following the same logic:
is_even(k) = is_odd(k - 1) = not is_even(k - 1). Now we know how is_even() works so is_even(k - 1) is True and and hence not is_even(k - 1) which is is_even(k) shall be False as intended. You can expect to see similar behaviour regarding is_odd().
Sorry for the long reply! All in all you're better off doing x % 2 == 0 đ