小菜鸡终于抓住了一道会写的题。然而也是遇到了不少问题。
首先,将leetcode上的回答格式粘贴到sublime里会变成空格和tab混用的状态,于是各种报indent error。这个最后用sublime里view->indentation->convert indentation to spaces解决了。
然后的代码是(错误代码错误代码错误代码):
class Solution(object):
def hammingDistance(self, x, y):
if x>y:
x,y=y,x
xb = bin(x).lstrip('0b')
yb = bin(y).lstrip('0b')
count = int(0)
for i in range(1,len(yb)+1):
if i<=len(xb):
if xb[-i]!=yb[-i]:
count+=1
elif yb[-i]==1:
count+=1
return count
各种错误。比如输入0,6,输出应为2。然而结果为0。很是苦恼。思索了半天,发现问题在elif一句中,yb是str类,用来比较的应该是str的1,即'1'。尴尬。后更改,ac。
class Solution(object):
def hammingDistance(self, x, y):
if x>y:
x,y=y,x
xb = bin(x).lstrip('0b')
yb = bin(y).lstrip('0b')
count = int(0)
for i in range(1,len(yb)+1):
if i<=len(xb):
if xb[-i]!=yb[-i]:
count+=1
elif yb[-i]=='1':
count+=1
return count
这一道题也算是让我一下体验了python这门语言的两个大坑了——indent和弱类型。
下一步看看discuss里大神们是怎么实现的。
看了discuss,果然是被虐了。自己想到bin方法的确不错,但是没有想到python的位运算符们:
参考yuyuyu0905的答案,使用按位异或运算符结合str.count()方法,即可得到一行python的答案:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
另外还看到了YDD9的答案:list comprehension in python is fast
return len([i for i in format(x ^ y, 'b') if i=='1'])
其中 format 是built-in方法:
format
(
value
[,
format_spec
]
)
Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.
The default format_spec is an empty string which usually gives the same effect as calling str(value)
.
A call to format(value, format_spec)
is translated to type(value).__format__(value, format_spec)
which bypasses the instance dictionary when searching for the value’s __format__()
method. A TypeError
exception is raised if the method search reachesobject
and the format_spec is non-empty, or if either the format_spec or the return value are not strings.