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.
Explanation:
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))
Sample Output:
4 0
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to find the single number in a list that doesn't occur twice.
Next: Write a Python program to find the single element appears once in a list where every element appears four times except for one.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics