Cho mảng số nguyên dương nhập từ người dùng. Nhiệm vụ tìm số xuất hiện số lần lẻ.
Ví dụ
Input: A=[2, 4, 7, 7, 4, 2, 2] Output: 2
Thuật toán
Bước 1: Nhập phần tử mảng. Bước 2: Viết lambda expression và áp dụng. Bước 3: Reduce function trên list cho đến khi chỉ còn một giá trị. Bước 4: Biểu thức reduce a^b thành giá trị đơn. Bước 5: a bắt đầu từ 0, b bắt đầu từ 1.
Ví dụ mã
# Chương trình Python tìm số xuất hiện số lần lẻ
# dùng Lambda expression và reduce function
from functools import reduce
def timeoccurrance(inp):
print("RESULT ::>", reduce(lambda a, b: a ^ b, inp))
# Driver program
if __name__ == "__main__":
A = list()
n1 = int(input("Enter the size of the List ::"))
print("Enter the Element of List ::")
for i in range(int(n1)):
k = int(input(""))
A.append(k)
timeoccurrance(A)
Kết quả
Enter the size of the List :: 7 Enter the Element of List :: 1 2 3 2 3 1 3 RESULT ::> 3