diff --git a/DIRECTORY.md b/DIRECTORY.md index 0f9859577493..5fc35ac3d212 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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) diff --git a/bit_manipulation/binary_parity_pattern.py b/bit_manipulation/binary_parity_pattern.py new file mode 100644 index 000000000000..d2691e38c77f --- /dev/null +++ b/bit_manipulation/binary_parity_pattern.py @@ -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()