Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Find Number Occurring Odd Number of Times ด้วย Lambda และ Reduce Python

ได้ลิสต์ตัวเลข หาตัวเลขที่ปรากฏจำนวนครั้งเป็นคี่ (Odd) โดยใช้ lambda และ reduce (XOR Operation)

หลักการ

XOR ของตัวเลขเดียวกันคู่กันจะเป็น 0 (a ^ a = 0) ตัวที่ปรากฏคี่ครั้งจะเหลืออยู่

การติดตั้งใน Python

from functools import reduce

def odd_count(lst):
    return reduce(lambda x, y: x ^ y, lst)

listA = [12, 34, 12, 12, 34]
print("Given list:", listA)
print("Element occurring odd times:", odd_count(listA))  # 12

ข้อจำกัด

วิธีนี้ใช้ได้ก็ต่อเมื่อมี ตัวเลขเพียง 1 ตัว ที่ปรากฏครั้งคี่ หากมีหลายตัว ต้องใช้วิธีอื่น (เช่น Counter)