Tuple XOR Operation ใน Python
เมื่อต้องการทำ Operation XOR (Exclusive OR) บน Tuple สองตัวแบบ Element-wise สามารถใช้ zip() และ Generator Expression ได้
XOR Operator (^)
ใน Python ใช้ ^ สำหรับ Bitwise XOR เปรียบเทียบ Bit ตรงกัน: ต่างกันให้ 1, เหมือนกันให้ 0
ตัวอย่างโค้ด
my_tuple_1 = (7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)
print("The first tuple is : ")
print(my_tuple_1)
print("The second tuple is : ")
print(my_tuple_2)
# zip จับคู่ แล้ว XOR กัน
my_result = tuple(elem_1 ^ elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))
print("The XORed tuple value is : ")
print(my_result)
ผลลัพธ์
The first tuple is : (7, 8, 3, 4, 3, 2) The second tuple is : (9, 6, 8, 2, 1, 0) The XORed tuple value is : (14, 14, 11, 6, 2, 2)
คำอธิบาย
- กำหนด Tuple 2 ตัว และแสดงผล
- ใช้
zip()จับคู่ Element ที่ Index ตรงกัน - Generator Expression ทำ XOR (
elem_1 ^ elem_2) - แปลงเป็น Tuple ด้วย
tuple() - เก็บผลลัพธ์และแสดง
การคำนวณ XOR แบบ Binary
| Index | Tuple 1 (Binary) | Tuple 2 (Binary) | XOR Result | Decimal |
|---|---|---|---|---|
| 0 | 7 = 0111 | 9 = 1001 | 1110 | 14 |
| 1 | 8 = 1000 | 6 = 0110 | 1110 | 14 |
| 2 | 3 = 0011 | 8 = 1000 | 1011 | 11 |
| 3 | 4 = 0100 | 2 = 0010 | 0110 | 6 |
| 4 | 3 = 0011 | 1 = 0001 | 0010 | 2 |
| 5 | 2 = 0010 | 0 = 0000 | 0010 | 2 |
Bitwise Operators อื่นๆ
# AND (&)
tuple(a & b for a, b in zip(t1, t2))
# OR (|)
tuple(a | b for a, b in zip(t1, t2))
# NOT (~) - Unary
tuple(~a for a in t1)
# Left Shift (<<)
tuple(a << 1 for a in t1)
# Right Shift (>>)
tuple(a >> 1 for a in t1)
ใช้ NumPy
import numpy as np
result = tuple(np.bitwise_xor(np.array(t1), np.array(t2)))