Python Program to Find the Number Occurring Odd Number of Times in a List

This is a Python program to find the element that occurs odd number of times in a list.

Problem Description

A list is given in which all elements except one element occurs an even number of times. The problem is to find the element that occurs an odd number of times.

Problem Solution

1. The function find_odd_occurring is defined.
2. It takes a list as argument which has only one element that occurs an odd number of times.
3. The function returns that element.
4. It finds the element by XORing all elements in the list.
5. Since the XOR operation is commutative and associative and it satisfies p XOR p = 0 and p XOR 0 = p, the element that occurs an odd number of times is the result.

Program/Source Code

Here is the source code of a Python program to find element that occurs odd number of times in a list. The program output is shown below.

def find_odd_occurring(alist):
    """Return the element that occurs odd number of times in alist.
 
    alist is a list in which all elements except one element occurs an even
    number of times.
    """
    ans = 0
 
    for element in alist:
        ans ^= element
 
    return ans
 
 
alist = input('Enter the list: ').split()
alist = [int(i) for i in alist]
ans = find_odd_occurring(alist)
print('The element that occurs odd number of times:', ans)
Program Explanation

1. The user is prompted to enter the list.
2. find_odd_occurring is called on the list.
3. The result is then displayed.

advertisement
advertisement
Runtime Test Cases
Case 1:
Enter the list: 15 22 10 33 22 33 15 1 1 15 15
The element that occurs odd number of times: 10
 
Case 2:
Enter the list: 3
The element that occurs odd number of times: 3
 
Case 3:
Enter the list: 1 2 3 1 2 3 4 1 2 3 1 2 4 3 4
The element that occurs odd number of times: 4

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.