[英]Understanding recursive odd/even functions
我目前正在从http://www.sololearn.com/Play/Python学习python,但无法理解为什么此代码有效。
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))
我了解了递归在斐波那契和阶乘上的工作原理,但是我无法解决这个问题。
它基于对均匀性的归纳定义:
“奇数”显然是“不偶数”。
代码采用此定义,并使用递归向后检查。
is_even'
的基本情况解析为True
。 由于is_odd(x)
not is_even(x)
返回not is_even(x)
,因此True
值将是is_odd
返回的表达式的is_odd
。 问题是,将否定 True
值多少次。 通过跟踪呼叫,您可以看到当x
为奇数时,它会被否定偶数次,从而“保留”其真实性[例如: x=3
==> (not (not (not (not True))))
== True
],并且当x
为偶数时,奇数次,因此“失去”它的真实性[例如: x=2
==> (not (not (not True)))
== False
]。 逻辑中可能有一个术语将多重否定的一般属性命名为。
递归函数确实是教授递归的一种不好的方法,只有在有用时才应应用递归。 实际上,用负数测试这些函数,您将得到RuntimeError: maximum recursion depth exceeded
错误。
要检查奇偶校验数字,最好使用%
运算符或&
和and运算符,即:
def is_even(x):
return (x & 1) == 0
def is_odd(x):
return (x & 1) == 1
就是说,我认为@Elazar和@DAXaholic答案应该为您提供有关该越野车递归函数的一些见解,并让您对此有所保留。
一些提示:
0 -> True
1 -> not True
2 -> not not True
3 -> not not not True
...
等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.