📜  Python|使用 Lambda 表达式和 reduce函数查找出现奇数次的数字

📅  最后修改于: 2022-05-13 01:55:19.889000             🧑  作者: Mango

Python|使用 Lambda 表达式和 reduce函数查找出现奇数次的数字


给定一个正整数数组。所有数字都出现偶数次,除了一个出现奇数次的数字。在 O(n) 时间和常数空间中找到数字。

例子:

Input :  [1, 2, 3, 2, 3, 1, 3]
Output :  3

对于这个问题,我们有现有的解决方案,请参考 Find the Number Occurring Odd Number of Times 链接。我们将使用 Reduce(expression, iterable) 方法在Python中快速解决这个问题。

# Python program to Find the Number 
# Occurring Odd Number of Times
# using Lambda expression and reduce function
  
from functools import reduce
  
def oddTimes(input):
     # write lambda expression and apply
     # reduce function over input list
     # until single value is left
     # expression reduces value of a ^ b into single value
     # a starts from 0 and b from 1
     # ((((((1 ^ 2)^3)^2)^3)^1)^3)
     print (reduce(lambda a, b: a ^ b, input))
  
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 2, 3, 1, 3]
    oddTimes(input)

输出:

3