Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
* [Binary Twos Complement](bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](bit_manipulation/binary_xor_operator.py)
* [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py)
* [Binary Parity Pattern](bit_manipulation/binary_parity_pattern.py)
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
* [Excess 3 Code](bit_manipulation/excess_3_code.py)
Expand Down
47 changes: 47 additions & 0 deletions bit_manipulation/binary_parity_pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
binary_parity_pattern.py
========================

Generates a binary parity pattern based on the cumulative sum of bits
in the binary representation of an integer.

Reference:
https://en.wikipedia.org/wiki/Parity_(mathematics)
"""


def binary_parity_pattern(number: int) -> str:
"""
Return a binary parity pattern string for a given integer.

>>> binary_parity_pattern(13)
'0b1001'
>>> binary_parity_pattern(7)
'0b101'
>>> binary_parity_pattern(4)
'0b111'
>>> binary_parity_pattern(0)
'0b0'
"""
if number < 0:
raise ValueError("Number must be non-negative")

if number == 0:
return "0b0"

binary_str = bin(number)[2:]
cum_sum = 0
pattern = []

for bit in binary_str:
cum_sum += int(bit)
pattern.append(str(cum_sum % 2))

result = "".join(pattern).lstrip("0")
return "0b" + (result if result else "0")


if __name__ == "__main__":
import doctest

doctest.testmod()