หาตัวเลขที่เกิดขึ้นจำนวนครั้งคี่ในอาร์เรย์จำนวนเต็มบวก โดยใช้ XOR property: a ^ a = 0, a ^ 0 = a ด้วย functools.reduce และ lambda
ตัวอย่าง
Input: [2,4,7,7,4,2,2] Output: 2
อัลกอริทึม
- รับอาร์เรย์
- ใช้
reduce(lambda a,b: a^b, arr) - ผลลัพธ์คือตัวเลขที่เกิดครั้งคี่
โค้ดตัวอย่าง
from functools import reduce
def timeoccurrance(inp):
print("RESULT:", reduce(lambda a,b: a^b, inp))
if __name__ == "__main__":
A = []
n = int(input("Enter the size of the List: "))
print("Enter the Elements:")
for _ in range(n):
A.append(int(input()))
timeoccurrance(A)
ผลลัพธ์
Enter the size of the List: 7 Enter the Elements: 1 2 3 2 3 1 3 RESULT: 3