Skip to content

Commit 1e70a87

Browse files
committed
fix:correct binary_parity_pattern doctest and return format
1 parent 9dc42bb commit 1e70a87

1 file changed

Lines changed: 16 additions & 16 deletions

File tree

bit_manipulation/binary_parity_pattern.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,41 @@
11
"""
2-
=======================================
3-
⚖️ Binary Parity Pattern
4-
=======================================
2+
binary_parity_pattern.py
3+
========================
54
6-
Generates a binary pattern where each bit represents
7-
the parity (even/odd) of the cumulative sum of bits
8-
in the original binary representation.
5+
Generates a binary parity pattern based on the cumulative sum of bits
6+
in the binary representation of an integer.
97
10-
Example:
11-
13 (1101) → cumulative sums [1,2,3,4]
12-
parity pattern = 1010
8+
Reference:
9+
https://en.wikipedia.org/wiki/Parity_(mathematics)
1310
"""
1411

1512

1613
def binary_parity_pattern(number: int) -> str:
1714
"""
18-
Generate parity pattern of cumulative binary sums.
15+
Return a binary parity pattern string for a given integer.
1916
2017
>>> binary_parity_pattern(13)
2118
'0b1010'
2219
>>> binary_parity_pattern(7)
2320
'0b111'
2421
>>> binary_parity_pattern(4)
2522
'0b10'
23+
>>> binary_parity_pattern(0)
24+
'0b0'
2625
"""
2726
if number < 0:
28-
number = abs(number)
27+
raise ValueError("Number must be non-negative")
2928

30-
binary = bin(number)[2:]
31-
parity_pattern = ""
29+
binary_str = bin(number)[2:]
3230
cum_sum = 0
31+
pattern = []
3332

34-
for bit in binary:
33+
for bit in binary_str:
3534
cum_sum += int(bit)
36-
parity_pattern += str(cum_sum % 2)
35+
pattern.append(str(cum_sum % 2))
3736

38-
return "0b" + parity_pattern
37+
result = "0b" + "".join(pattern)
38+
return result if result != "0b" else "0b0"
3939

4040

4141
if __name__ == "__main__":

0 commit comments

Comments
 (0)