[英]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.