+ 1
Can anyone explain about 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_even (17)) print (is_odd (23))
10 Answers
+ 2
Try a small number. For example:
is_even(1) - > return is_odd(0)
is_odd(0) - > return not is_even(0)
is_even(0) - > return True
Then work backwards:
not is_even(0) - > not True - > False
is_odd(0) - > False
is_even(1) - > False
Put another way,
x is odd exactly when x is not even.
x is even exactly when x-1 is odd.
This code counts down all the way to 0, and then says 0 is even.
0
This code defines two functions: is_even and is_odd. The is_even function takes an integer x as input and returns True if x is even, and False otherwise. The is_odd function takes an integer x as input and returns True if x is odd, and False otherwise.
The is_even function first checks if x is equal to 0. If it is, it returns True, because 0 is an even number. If x is not equal to 0, the function returns the result of calling the is_odd function with an input of x-1.
0
The is_odd function returns the opposite of the result of calling the is_even function with an input of x.
Finally, the code prints the result of calling the is_even function with an input of 17, and the result of calling the is_odd function with an input of 23. The output will be False and True, respectively.
0
Here is an updated version of the return_is_odd function that correctly returns whether the input number is odd:
def return_is_odd(x):
if x == 0:
return False
elif x == 1:
return True
else:
return return_is_odd(x-2)
if you call return_is_odd(5), the function will first check if x == 0, which is False. It will then check if x == 1, which is also False. Finally, it will call itself with x-2, which is return_is_odd(3). This recursive call will repeat the process until x is either 0 or 1, at which point the function will return the appropriate value. In this case, the final call will be return_is_odd(1), which will return True.
0
Looks like recursion.
I guess any number above 997 will cause RecursionError.
0
Better result can be archived as follows:
def is_even(x):
return not bool(bin(x)[-1])
is_odd = lambda x: not is_even(x)
😉
0
"""
I need to correct my code a little bit, because there was a symantical error ;)
sorry for this!
Here is the updated code with just minor changes
first convert the input to bianry, then to integer and finally to inverted boolian
"""
def is_even(x):
return not bool(int(bin(x)[-1]))
is_odd = lambda x: not is_even(x)