|
1 | 1 | """ |
2 | | -======================================= |
3 | | -⚖️ Binary Parity Pattern |
4 | | -======================================= |
| 2 | +binary_parity_pattern.py |
| 3 | +======================== |
5 | 4 |
|
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. |
9 | 7 |
|
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) |
13 | 10 | """ |
14 | 11 |
|
15 | 12 |
|
16 | 13 | def binary_parity_pattern(number: int) -> str: |
17 | 14 | """ |
18 | | - Generate parity pattern of cumulative binary sums. |
| 15 | + Return a binary parity pattern string for a given integer. |
19 | 16 |
|
20 | 17 | >>> binary_parity_pattern(13) |
21 | 18 | '0b1010' |
22 | 19 | >>> binary_parity_pattern(7) |
23 | 20 | '0b111' |
24 | 21 | >>> binary_parity_pattern(4) |
25 | 22 | '0b10' |
| 23 | + >>> binary_parity_pattern(0) |
| 24 | + '0b0' |
26 | 25 | """ |
27 | 26 | if number < 0: |
28 | | - number = abs(number) |
| 27 | + raise ValueError("Number must be non-negative") |
29 | 28 |
|
30 | | - binary = bin(number)[2:] |
31 | | - parity_pattern = "" |
| 29 | + binary_str = bin(number)[2:] |
32 | 30 | cum_sum = 0 |
| 31 | + pattern = [] |
33 | 32 |
|
34 | | - for bit in binary: |
| 33 | + for bit in binary_str: |
35 | 34 | cum_sum += int(bit) |
36 | | - parity_pattern += str(cum_sum % 2) |
| 35 | + pattern.append(str(cum_sum % 2)) |
37 | 36 |
|
38 | | - return "0b" + parity_pattern |
| 37 | + result = "0b" + "".join(pattern) |
| 38 | + return result if result != "0b" else "0b0" |
39 | 39 |
|
40 | 40 |
|
41 | 41 | if __name__ == "__main__": |
|
0 commit comments