This is a Python program to find the element that occurs odd number of times in a list.
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.
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.
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)
1. The user is prompted to enter the list.
2. find_odd_occurring is called on the list.
3. The result is then displayed.
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.
- Practice Programming MCQs
- Apply for Python Internship
- Check Python Books
- Apply for Programming Internship
- Check Information Technology Books