w3resource logo


Python Exercises

Python Challenges: Find the single element in a list where every element appears three times except for one

Python Challenges - 1: Exercise-13 with Solution

Write a Python program to find the single element in a list where every element appears three times except for one.

Input : [5, 3, 4, 3, 5, 5, 3]
Output : 4

Explanation :

Python: Find the single element in a list where every element appears three times except for one.

Sample Solution :-

Python Code :

def single_number(arr):
    ones, twos = 0, 0
    for x in arr:
        ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
    assert twos == 0
    return ones
arr1 = [5, 3, 4, 3, 5, 5, 3]
arr2 = [-1, 1, 1, -1, -1, 1, 0]
print(single_number(arr1))
print(single_number(arr2))

Output :

4                                                                       
0

Flowchart:

Python Flowchart: Find the single element in a list where every element appears three times except for one

Python Code Editor:

def single_number(arr):
    ones, twos = 0, 0
    for x in arr:
        ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
    assert twos == 0
    return ones
arr1 = [5, 3, 4, 3, 5, 5, 3]
arr2 = [-1, 1, 1, -1, -1, 1, 0]
print(single_number(arr1))
print(single_number(arr2))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables