w3resource logo

:

Python Exercises

Python Challenges: Find two elements once in a list where every element appears exactly twice in the list

Python Challenges - 1: Exercise-15 with Solution

Write a Python program to find two elements once in a list where every element appears exactly twice in the list.

Explanation :

Python: Find two elements once in a list where every element appears exactly twice in the list

Sample Solution:-

Python Code:

import functools
import operator
def two_numbers(arr):
    x_xor_y = functools.reduce(operator.xor, arr)
    bit =  x_xor_y & -x_xor_y
    result = [0, 0]
    for i in arr:
        result[bool(i & bit)] ^= i
    return result

print(two_numbers([1, 2, 1, 3, 2, 5]))
print(two_numbers([11, 5, 3, 7, 0, 5, 3, 6, 7, 11]))

Sample Output:

[5, 3]
[0, 6]

Flowchart:

Python Flowchart: Find two elements once in a list where every element appears exactly twice in the list

Python Code Editor:

Improve this sample solution and post your code through Disqus