Python程序使用Lambda表达式和reduce函数查找出现奇数次的数字
这里给出了一个用户输入的正整数数组。我们的任务是找出出现奇数次的数字。
示例
Input : A=[2, 4, 7, 7, 4, 2, 2] Output : 2
算法
Step 1: Input Array element. Step 2: Write lambda expression and apply. Step 3: Reduce function over the input list until a single value is left. Step 4: Expression reduces the value of a^b into a single value. Step 5: a starts from 0 and b starts from 1.
示例代码
#查找数字的Python程序
#发生奇数次
#使用Lambda表达式和reduce函数
from functools import reduce
def timeoccurrance(inp):
print ("RESULT ::>",reduce(lambda a, b: a ^ b, inp)))
#驱动程序
if __name__ == "__main__":
A=list()
n1=int(input("输入列表的大小::"))
print("输入列表元素::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
timeoccurrance(A)输出结果输入列表的大小:: 7 输入列表元素:: 1 2 3 2 3 1 3 RESULT ::> 3