Write Python program to get data items from a list appearing odd number of times

Python Program to Find the Number Occurring Odd Number of Times

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 :

Input : arr = {1, 2, 3, 2, 3, 1, 3} Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5} Output : 5

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

PythonServer Side ProgrammingProgramming

When it is required to find an element that occurs odd number of times in a list, a method can be defined. This method iterates through the list and checks to see if the elements in the nested loops match. If they do, the counter is incremented. If that count is not divisible by 2, the specific element of the list is returned as the result. Otherwise, -1 is returned as the result.

Below is a demonstration of the same −

How Do You Print Odd Numbers From a List in Python?

To print odd numbers from a list of numbers you can use the Python modulo operator, related to the mathematical concept of remainder.

When you divide an odd number by 2 the remainder of the division is 1. When you divide an even number by 2 the remainder of the division is 0.

Let’s use this concept and a Python for loop to print odd numbers from a list.

def get_odd_numbers(numbers): odd_numbers = [] for number in numbers: if number % 2 == 1: odd_numbers.append(number) return odd_numbers

Before starting the for loop we define an empty list, then at every iteration of the for loop we add odd numbers to the list.

numbers = [2, 3, 6, 8, 13, 45, 67, 88, 99, 100] print(get_odd_numbers(numbers)) [output] [3, 13, 45, 67, 99]


A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts number of occurrences of the element picked by outer loop. Time complexity of this solution is O(n2).



Below is the implementation of the brute force approach :

Python Challenges: Find the single number which occurs odd numbers and other numbers occur even number

Last update on February 26 2020 08:09:27 (UTC/GMT +8 hours)

Video liên quan

Postingan terbaru

LIHAT SEMUA