Python program to find odd occurrences of a number in a sequence


The odd occurrences of the given sequence is nothing but finding the number of times a number is present in the given sequence, if the number occurred odd number of times then the number is said to be occurred odd number of times, else no. 
Example: 
seq = {1,2,3,4,2,3,4,1,1}
output: 1 occurred odd no.of times

Here, in the above program the number 1 occurred odd no.of times and remaining numbers occurred even no.of times. So, the output is 1.

The source code for the given example is written below

Python program:


Method 1:
array=[1,2,3,2,3,1,4,5,3,5,4]  #array
res=0   #variable result
for i in array:
    res=res^i     #xor operation
print("The number occurred odd no.of times is : "res)

Output:

The number occurred odd no.of times is : 3

Program:

Method 2:
array=[1,2,3,2,3,1,4,5,3,5,4];#array
for i in range(0,len(array)):
    count=0
    for j in range(0,len(array)):
      if array[i]==array[j]:
        count+=1
    if count%2!=0:
     print("The number occurred odd no.of times is : ",array[i])
     break

Output:

The number occurred odd no.of times is : 3

Post a Comment

0 Comments