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

โปรแกรม Python หาตัวเลขที่เกิดจำนวนครั้งคี่ด้วย Lambda และ reduce


หาตัวเลขที่เกิดขึ้นจำนวนครั้งคี่ในอาร์เรย์จำนวนเต็มบวก โดยใช้ XOR property: a ^ a = 0, a ^ 0 = a ด้วย functools.reduce และ lambda

ตัวอย่าง

Input: [2,4,7,7,4,2,2]
Output: 2

อัลกอริทึม

  1. รับอาร์เรย์
  2. ใช้ reduce(lambda a,b: a^b, arr)
  3. ผลลัพธ์คือตัวเลขที่เกิดครั้งคี่

โค้ดตัวอย่าง

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