Skip to content

Commit cbe8a32

Browse files
committed
Add binary parity pattern implementation and update directory
1 parent c79034c commit cbe8a32

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
* [Binary Twos Complement](bit_manipulation/binary_twos_complement.py)
3838
* [Binary Xor Operator](bit_manipulation/binary_xor_operator.py)
3939
* [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py)
40+
* [Binary Parity Pattern](bit_manipulation/binary_parity_pattern.py)
4041
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
4142
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
4243
* [Excess 3 Code](bit_manipulation/excess_3_code.py)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
=======================================
3+
⚖️ Binary Parity Pattern
4+
=======================================
5+
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.
9+
10+
Example:
11+
13 (1101) → cumulative sums [1,2,3,4]
12+
parity pattern = 1010
13+
"""
14+
15+
def binary_parity_pattern(number: int) -> str:
16+
"""
17+
Generate parity pattern of cumulative binary sums.
18+
19+
>>> binary_parity_pattern(13)
20+
'0b1010'
21+
>>> binary_parity_pattern(7)
22+
'0b111'
23+
>>> binary_parity_pattern(4)
24+
'0b10'
25+
"""
26+
if number < 0:
27+
number = abs(number)
28+
29+
binary = bin(number)[2:]
30+
parity_pattern = ""
31+
cum_sum = 0
32+
33+
for bit in binary:
34+
cum_sum += int(bit)
35+
parity_pattern += str(cum_sum % 2)
36+
37+
return "0b" + parity_pattern
38+
39+
40+
if __name__ == "__main__":
41+
import doctest
42+
doctest.testmod()

0 commit comments

Comments
 (0)