[英]Even and Odd numbers with recursion in Python
我正在尝试通过递归的方式解决“ is_even”和“ is_odd”函数。 我不明白该函数的编写结果如何评估为False,或者任何非0的结果如何评估为True。 我在teamtreehouse.com工作区中对其进行了仔细检查,以确保它可以正常工作,但是我不知道它如何工作。
我知道通过递归递减,但是我不知道is_odd(x)是如何工作的。 如果is_odd(x)仅对is_even中的所有值求反,那么为什么所有数字都不为True? 还是假的?
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
# Does this negate the function of is_even(x)?
# Does that negating mean returning False, or sending to else block?
# If the negating does automatically sends to the else block
# After we get here, do we ever land at True in is_even(x)?
# If not, how do we ever land at False?
print(is_even(1))
print(is_even(2))
print(is_even(3))
x = 0
is_even: True
x = 1
is_even:
is_odd(0):
is_even(0): True
not True: False
False
x = 2
is_even:
is_odd(1):
is_even(1): False
not False: True
True
x = 3
is_even:
is_odd(2):
is_even(2): True
not True: False
False
让我们以函数is_even(1)为例。 怎么了?
(1)
现在让我们以is_even(2)为例。 怎么了?
(2)
现在使用is_even(3)
(3)
再次对您的问题:
是的:正如您在我的示例中看到的那样,is_even(x)不会否定is_even(x)的结果 。
否。如果函数is_even(x)返回True,则不返回True。 如果函数is_even(x)返回False,则不False返回True。 因此它否定了is_even(x)的结果
正如您在我的示例中所看到的那样,由于您始终使用(x-1)来减小自变量,因此最终您最终将始终到达x = 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.