Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function

  • Last Updated : 20 Oct, 2018


Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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

We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solve this problem in python quickly using Reduce(expression, iterable) method.




# 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)

Output:

3
My Personal Notes arrow_drop_up
Recommended Articles
Page :