Sitemap

Python — Boolean延伸(truth priority & table、short-circuit、chained data comparison)

5 min readOct 11, 2022

--

之前Python — Numeric datatype(int、 fraction、complex、 boolean)裡關於Boolean裡的部分寫的相對少一點,獨立的把這一部分Boolean的寫在這篇,因為覺得這很有用及有趣。

文章簡介

  • Basic Boolean Rule
  • Boolean Priority
  • Boolean Short-Circuit Evaluation
  • Chained Data Comparison

Basic Boolean Rule

跟特定Python程式、運用無關,只是當複習跟補充知識紀錄:

  • Commutativity(交換性)
A or B == B or AA and B == B and A
  • Associativity(相依性)
(A or B) or C == A or B or C(A and B) and C == A and B and C
  • Distributivity(分配性)
(A or B) and C == (A and C) or (B and C)
(A and B) or C == (A or C) and (B or C)
  • De Mogan’s theorem
not (A or B) == not A and not B
not (A and B) == not A or not B

Boolean Priority

在Python中,有一些運算符號最終返回的結果是Boolean的True/False,而這些運算符號也有先做後做的規則。

Get John’s stories in your inbox

Join Medium for free to get updates from this writer.

Priority:

  • Ex1
True or True and False #Result is True
  • Ex2
9 > 3 or 4 in [1,2,3,4] and 3!= 2 #Result is True

Boolean Short-Circuit Evaluation

寫Boolean Short-Circuit前先附上Boolean value的真值表:

Press enter or click to view image in full size

而Boolean Short-Circuit的概念是Python在評估Boolean value時的一種節省運算的方式,概念是:

  • X or Y will return True without evaluating Y if X is True
  • X and Y will return False without evaluating Y if X is False
Press enter or click to view image in full size

從真值表可以看到當我們在評估X or Y時,若兩者其中一個為True則X or Y必為True,因此Python實際上只先評估了前面的X,若為True,則直接return結果為True,不會多花時間評估後面的Y。

相反道理,在評估X and Y時,若兩者其中一個為False,則X and Y必為False,因此Python先評估前面的X,若為False,則直接回傳False。

Application to “or”、"and"

Short-Circuit的運算也被應用到了Python中的and、or運算,為:

  • X or Y:If X’s truth value is truthy, then return X, else return Y
  • X and Y:If X’s truth value is False, then return X, else return Y

這是一個非常漂亮的應用,因為return的結果不單單只是Boolean,而是實際的物件,所以我們可以舉例應用在以下情況:今天我們想要用Short-Circuit Evaluation的概念計算n筆資料的平均值,當input n是0的時候,運算回傳0,而不為0的情況下回傳計算的平均值:

#Computing an average:input sum, n, sometimes n is nonzero, sometimes it is.print(n and sum/n) 

只要一行的程式就可以寫出這樣的計算,當n=0的情況下,and前面的truth value會=False,Python會直接回傳n,也就是0;當n不為0的情況下,and就面的truth value=True,Python會進一步計算sum/n並回傳其結果。

Chained Data Comparison

最後補充多個Boolean比較的規則,若有多個比較,最後評估一個總體的結果,則規則為計算個別Boolean並且用and連接。

a == b ==c -> a==b and b==c
a < b < c -> a < b and b < c
a < b < c < d -> a < b and b < c and c < d

--

--