Created
June 5, 2014 15:38
-
-
Save GuillermoPena/26128d93e70a9ee6a217 to your computer and use it in GitHub Desktop.
CheckIO - Electronic Station Challenge 3 : Hamming Distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# CheckIO - Electronic Station Challenge 3 : Hamming Distance | |
# http://checkio.org | |
# The Hamming distance between two binary integers is the number of bit positions that differs | |
# For example: | |
# | |
# 117 = 0 1 1 1 0 1 0 1 | |
# 17 = 0 0 0 1 0 0 0 1 | |
# H = 0+1+1+0+0+1+0+0 = 3 | |
def checkio(n, m): | |
nbin=bin(n)[2:] # Converting to binary | |
mbin=bin(m)[2:] | |
nbin=nbin.zfill(max(len(nbin),len(mbin))) # Adding 0's to de left | |
mbin=mbin.zfill(max(len(nbin),len(mbin))) | |
hamming=0 | |
for idx in range(0,len(mbin)): | |
if mbin[idx]!=nbin[idx]: hamming+=1 # Counting 1's in result | |
return hamming | |
if __name__ == '__main__': | |
#These "asserts" using only for self-checking and not necessary for auto-testing | |
assert checkio(117, 17) == 3, "First example" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment