forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparity.py
More file actions
43 lines (35 loc) · 850 Bytes
/
Copy pathparity.py
File metadata and controls
43 lines (35 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Author : Basuki Nath
Date : 2025-10-04
Simple parity utility for integers.
The parity is 1 when the number of set bits is odd, otherwise 0.
"""
def parity(number: int) -> int:
"""
Return 1 if `number` has an odd number of set bits, otherwise 0.
>>> parity(0)
0
>>> parity(1)
1
>>> parity(2) # 10b -> one set bit
1
>>> parity(3) # 11b -> two set bits
0
>>> parity(1023) # 10 ones -> even
0
>>> parity(-1)
Traceback (most recent call last):
...
ValueError: number must not be negative
"""
if number < 0:
raise ValueError("number must not be negative")
# Kernighan's algorithm toggling parity
p = 0
while number:
p ^= 1
number &= number - 1
return p
if __name__ == "__main__":
import doctest
doctest.testmod()