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

In this program, we will write a Python program to find the number that occurs an odd number of times in a given list of integers. We will use a simple approach and bitwise XOR operation to solve this problem efficiently.

Problem Statement

Given a list of integers, where all numbers occur even times except for one number that occurs odd times, we need to find that number.

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

def find_odd_occurrence(arr):
    result = 0
    for num in arr:
        result ^= num 

    return result


input_list = list(map(int, input("Enter the list of integers separated by spaces: ").split()))

odd_occurrence = find_odd_occurrence(input_list)


print("The number occurring odd number of times is: {odd_occurrence}")

How it works

  1. The program defines a function find_odd_occurrence that takes a list of integers as input.
  2. Inside the function, a variable result is initialized to 0. We will use this variable to store the XOR of all elements in the list.
  3. We iterate through each number in the list and perform a bitwise XOR operation with the result variable.
  4. XOR has a property that if we XOR a number with itself, the result is 0. So, when all even occurrences are XORed, they cancel out and the remaining value is the number occurring an odd number of times.
  5. The final result is returned by the function.

Input / output

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...