Single-bit error correction

Write codeMedium22 min

Your task

A memory controller protects each stored word by position parity. Number the bit positions 1, 2, 3 and upward starting at the least significant bit. A word is intact when the XOR of the positions of all its set bits is zero, and the controller only ever writes words that satisfy that. A stray particle flips at most one bit of a word while it sits in storage. words holds the values read back and word_bits is the width of each word. Return the repaired values in the same order. Leave a word alone when its position XOR is zero, otherwise read that XOR as the position that flipped and flip it back. When the position it names is greater than word_bits the word is beyond repair, so leave that one alone too.

Examples

repair_hamming_words(words: list[int], word_bits: int) -> list[int]
Example 1
Inputrepair_hamming_words([0], 8)
Output[0]
Example 2
Inputrepair_hamming_words([23], 8)
Output[7]
Example 3
Inputrepair_hamming_words([18], 5)
Output[18]