EPI 4.1: Computing The Parity Of A Word In Python.

We are looking at question 4.1 from Elements Of Programming Interviews Book. If you are applying for software engineering positions I highly recommend getting this book.

4.1 Computing the parity of a word

The parity of a binary word is 1 if the number of 1s i n the word is odd; otherwise, it is 0. For example, the parity of 1011 is 1, and the parity of 1000010000 is 0. Parity checks are used to detect single bit errors in data storage and communication. It is fairly straight forward to write code that computes the parity of a single 64-bit word.

Here is the video I created which walk you through solution provided in the book.

Elements Of Programming Interviews Question 4.1
def parity(x):
    result = 0
    while x:
        result ^= x & 1 # 0 ^ 10001 & 00001 : 1
                        # 1 ^ 0 : 1
        x = x >> 1
    return result