0

Lost

I can't understand this code 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)) print(is_even(1)) why the result is different ! !

3rd Jun 2017, 1:01 PM
Hachemi Raouf
Hachemi Raouf - avatar
4 Respuestas
+ 2
Let's see the function is_even(x). If x is 0, it returns true and otherwise returns is_odd(x-1), which returns not is_even(x-1). For example, let's analyze is_even(4). First, 4 is not 0, so is_even(4) returns is_odd(3), which is not is_even(3). And is_even(3) returns not is_even(2). Then is_even(4) is equal to not not is_even(2), same with is_even(2). Let's see 3 as example. is_even(3) is equal to not is_even(2), and is_even(2) is equal to not is_even(1). In other words, is_even(3) is is_even(1). By mathematical induction, we can get that is_even(x) is is_even(x-2), and is_even(x) is not is_even(x-1), which is same with is_odd(x-1). So is_even(1) is is_even(3), and it is not is_even(2), and it is not is_odd(1). So is_even(1) is not is_odd(1). Sorry for very long explanation..
3rd Jun 2017, 3:21 PM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 2
is_even(4) is is_odd(3), which is not is_even(3). is_even(3) is is_odd(2), which is not is_even(2). Then not is_even(3) is not is_odd(2), which is not not is_even(2). So is_even(4) is not is_even(3), and not not is_even(2), which is same with is_even(2).
4th Jun 2017, 12:12 AM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 1
why is_even (4) equal ti not not is_even (2) ??! it should be equal to is_odd (2) and is_odd (2) returns not is_even (2)🤔
3rd Jun 2017, 8:56 PM
Hachemi Raouf
Hachemi Raouf - avatar
+ 1
aaa now I understand so the key "not" is applied to both instructions of the fonction is_even "not is_even" returns false if x==0 and also (what I didn't notice ) it returns not is_od (x-1) thank you very much
4th Jun 2017, 6:37 AM
Hachemi Raouf
Hachemi Raouf - avatar