Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python XOR hammingDistance


The problem is

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 231.

I tried to use the ^ operator and just count the number of 1s in the resulting str. However it did not pass all the testing cases. For instance. 93^73 returns 11188 when it's supposed to return something else.

Here is my code:

#hamming distance
class Solution(object):
    def hammingDistance(x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        bin_x=int(bin(x)[2:])
    bin_y=int(bin(y)[2:])
    print(bin_x)
    print(bin_y)
    print(str(bin_x^bin_y))
    #.count('1'))
    hammingDistance(93,73)
like image 660
Eliza Avatar asked Nov 24 '25 11:11

Eliza


1 Answers

Your code here is incorrect: you should not convert the binary string into an integer (certainly not using base 10). For example, since bin(16)[2:] equals the string '1000', you can see that int(bin(16)[2:]) equals the actual integer 1000, which is not what you want!

In Python, the ^ operator for integers already does the looking at their binary representations for you. For example, in Python, 20 ^ 25 directly evaluates to 13, the correct answer, because

  • the binary representation of 20 is 10100
  • the binary representation of 25 is 11001
  • the binary representation of 13 is 01101

Now you can finish your approach by using Python's count function to count the number of 1 characters in the string. For example, '01101'.count('1') evaluates to 3.

like image 175
Zev Chonoles Avatar answered Nov 27 '25 01:11

Zev Chonoles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!