我正在尝试优化一个方法,该方法计算1
中每个数的二进制表示形式中的0 -> num
个数
# Example of how the below works, for clarity
#
# base => [0,1,1,2,1,2,2]
# index => 7
#
# {7} --
# bin(7) : 111
# bin(7-1) : 110
# 111 & 110 : 110 (6)
# append(base[6]+1) : append(3)
# //end 7
#
# base => [0,1,1,2,1,2,2,3]
def countBits(num):
index = 1
base = [0]
while(index <= num):
base.append(base[(index & (index - 1))]+1)
index += 1
return base
我想知道是否有一种方法可以将while循环转换成可以就地完成而不是循环的东西?我的第一个想法是。。。你知道吗
base.append(map(lambda index: base[(index & (index -1))]+1, num))
但这根本没用。。base
保持不变。我想我只是不完全理解map(lambda x:...)
语法的作用。我只用过几次,直接打电话。你知道吗
也许你想要这样的东西?你知道吗
结果:
相关问题 更多 >
编程相关推荐