Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Python program to find the number occurring odd number of times using Lambda expression and reduce function
We can find the number occurring an odd number of times in a list using a Lambda expression and the reduce() function from the functools module. The approach uses the XOR (^) bitwise operator − XORing a number with itself cancels it out (returns 0), so after XORing all elements, only the number that appears an odd number of times remains.
For example, given the following input −
ele = [10, 20, 20, 30, 40, 20, 30, 10, 40]
The output is 20, because 20 occurs three times (an odd count), while all other integers appear an even number of times and cancel out via XOR.
Using reduce() with Lambda
The reduce() function applies a given function cumulatively to the elements of a list, reducing it to a single value. Combined with a lambda that performs XOR, it processes the entire list in one pass ?
Example
from functools import reduce
def demoFunc(ele):
print("Number occurring odd times =", reduce(lambda a, b: a ^ b, ele))
if __name__ == "__main__":
ele = [10, 20, 20, 30, 40, 20, 30, 10, 40]
demoFunc(ele)
The output of the above code is ?
Number occurring odd times = 20
Example: With a Different Dataset
In this example, we use a different list of numbers to verify the same approach works correctly ?
from functools import reduce
def demoFunc(ele):
print("Occurring odd times =", reduce(lambda a, b: a ^ b, ele))
if __name__ == "__main__":
myList = [25, 35, 35, 40, 40, 40, 30, 25, 30]
demoFunc(myList)
The output of the above code is ?
Occurring odd times = 40
Here, 40 appears three times (odd) while 25, 35, and 30 each appear twice (even), so XOR reduces everything to 40.
Conclusion
The XOR bitwise operator combined with reduce() and a lambda expression provides an efficient way to find the element occurring an odd number of times. Note that this approach assumes exactly one element has an odd count; if multiple elements do, the result will be the XOR of all such elements.
