@@ -21,17 +21,17 @@ def hamming_encode(data_str: str) -> str:
2121 data = [int (x ) for x in data_str ]
2222 r = calculate_parity_bits (data )
2323 m = len (data )
24-
24+
2525 # Initialize code word with placeholders (0)
2626 code = [0 ] * (m + r )
27-
27+
2828 # Place data bits into non-parity positions
2929 j = 0
3030 for i in range (1 , len (code ) + 1 ):
3131 if (i & (i - 1 )) != 0 : # Not a power of 2
3232 code [i - 1 ] = data [j ]
3333 j += 1
34-
34+
3535 # Calculate parity bits using XOR logic
3636 for i in range (r ):
3737 parity_pos = 2 ** i
@@ -40,7 +40,7 @@ def hamming_encode(data_str: str) -> str:
4040 if j & parity_pos and j != parity_pos :
4141 parity_val ^= code [j - 1 ]
4242 code [parity_pos - 1 ] = parity_val
43-
43+
4444 return "" .join (map (str , code ))
4545
4646
@@ -55,12 +55,12 @@ def hamming_decode_and_correct(code_str: str) -> tuple[str, int]:
5555 """
5656 code = [int (x ) for x in code_str ]
5757 n = len (code )
58-
58+
5959 # Determine number of parity bits r
6060 r = 0
6161 while (2 ** r ) <= n :
6262 r += 1
63-
63+
6464 error_pos = 0
6565 # Check each parity bit syndrome
6666 for i in range (r ):
@@ -71,20 +71,21 @@ def hamming_decode_and_correct(code_str: str) -> tuple[str, int]:
7171 parity_sum ^= code [j - 1 ]
7272 if parity_sum != 0 :
7373 error_pos += parity_pos
74-
74+
7575 # Correct the error if detected
7676 if error_pos > 0 :
7777 code [error_pos - 1 ] ^= 1 # Flip the corrupted bit
78-
78+
7979 # Extract original data bits
8080 original_data = []
8181 for i in range (1 , n + 1 ):
8282 if (i & (i - 1 )) != 0 :
8383 original_data .append (code [i - 1 ])
84-
84+
8585 return "" .join (map (str , original_data )), error_pos
8686
8787
8888if __name__ == "__main__" :
8989 import doctest
90- doctest .testmod ()
90+
91+ doctest .testmod ()
0 commit comments