python基礎7:邏輯運算 與 位運算(note與運算巧用方法)

一、邏輯運算規則:
從左向右依次運算至倒數第二個元素,and運算執行判斷非空到and運算的最後一個並返回最後一個非空(若執行到and運算最後一個後整個邏輯值爲False,則返回第一個導致False的元素),or運算只需要執行至倒數第二個元素後非空(最後一個爲or運算)則返回最後一個or運算的左邊字符

'a' and 0 and 'b' and 'c' or 'd'
Out[10]: 'd'

'a' and 0 and 'b' and 'c'
Out[11]: 0

'a' and 0 and 'b' and None and 'c'
Out[12]: 0

0 and 'a' or 'b'
Out[14]: 'b'

1 and 'a' or 'b'
Out[15]: 'a'
'a' and 0  and  'b'  and  None  and  'c'
# 運算路徑:
'a' and 0 ---> False (# 0and運算第一個導致False的元素,若整個表達式爲False,則返回0)
        False and 'b' ---> False
                    False and None ---> False
                              False and 'c' ---> False  (# 整個表達式的結果爲False)

'a' and 0 and 'b' and 'c' or 'd' and 'e' or 'f'
out: 'e'
# 運算路徑:
'a' and 0 ---> False (# 0and運算第一個導致False的元素,若整個表達式爲False,則返回0)
        False and 'b' ---> False
                False and 'c' ---> False
                        False or 'd' ---> True 
                                True and 'e' ---> True
                                        True or 'f' ---> True (# 最後一次爲or運算,True非空即可直接返回,or運算實際不會執行)

二、位運算規則

  • 異或運算符(^):^ / __xor__ / bitwise_xor
  • 按位與運算符(&):& / __and__ / bitwise_and
  • 按位或運算符(|
  • 取反運算符(~
  • 左移運算符(<<
  • 右移運算符(>>

1、異或運算
原理:
參加運算的兩個數據,按二進制位進行“異或”運算。運算規則遵循 0^0=00^1=11^0=11^1=0。 即:參加運算的兩個對象,如果兩個相應位爲“異”(值不同),則該位結果爲1,否則爲0。

運算法則:
交換率:a^b=b^a
結合率:(a^b)^c=a^(b^c)
自反性:a^b^a=b^a^a=b
其它:a^0=aa^a=0

>>> bin(int('00000101', 2) ^ int('00001101', 2))
'0b1000'
>>> format(0b1000,'b')
'1000'
>>> int('00000101', 2),int('00001101', 2),int('1000', 2)
(5, 13, 8)
import numpy as np

a = np.array([0,1,-2,3,4])
b = np.array([-5,6,7,8,-9])
c = a ^ b
#c = a __xor__ b
print(a,b,c, sep='\n')
c_upzeros = np.take(c, np.where(c < 0))     # numpy.take()和numpy.where()用法
print(c_upzeros)
print(np.where(c < 0))     # 下標數組 (array([0, 2, 4], dtype=int64),)
print(np.where(c < 0)[0])  # [0 2 4]

2、取反運算符
原理:
按二進制位進行“取反”運算,運算規則:~1=0~0=1。對一個二進制數按位取反,即將0變1,1變0。
NOTE: 使一個數的最低位爲零,可以表示爲:a&~1

~1的值爲1111111111111110,再按“與”運算,最低位一定爲0。因爲“~”運算符的優先級比算術運算符、關係運算符、邏輯運算符和其他運算符都高。

3、與運算
原理:
二進制位進行“異或”運算。運算規則遵循: 1 & 1 = 11 & 0 = 00 & 1 = 00 & 0 = 0。全爲1則爲1。

判斷一個數是不是 2^n 的實現思路:
 2^0  1  00000001   -1 --> 00000000
 2^1  2  00000010   -1 --> 00000001
 2^2  4  00000100   -1 --> 00000011
 2^3  8  00001000   -1 --> 00000111
 2^4 16  00010000   -1 --> 00001111
 ...

按位與運算實現方法:if a & (a-1) == 0 then a == 2^n (耗時短)
實現思路:轉化爲二進制後進行按位與運算
思路聯想:1000個瓶子c有1瓶毒藥,用10只小白鼠試藥的方法:將1~1000的十進制數字轉換爲二進制數字

# 篩選出 2^n
d = np.arange(1,25)
e = d & (d - 1)
print(e)
f = d[d & (d - 1) == 0]     # 結果:2^n的數 [ 1  2  4  8 16]
#print(d[e == 0])
print(f)

參考:
按位與、或、異或等運算方法

Python獲取數字的二進制值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章