Total Hamming Distance
Posted andreaxgz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Total Hamming Distance相关的知识,希望对你有一定的参考价值。
1 class Solution(object): 2 def totalHammingDistance(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 bin_num = ["{0:b}".format(num) for num in nums] 8 zip_list = [] 9 for i in range(len(bin_num)): 10 for k in zip(bin_num, bin_num[i:]): 11 zip_list.append(k) 12 count = 0 13 len_list = [] 14 for x in zip_list: 15 for i in range(2): 16 len_list.append(len(x[i])) 17 max_len = max(len_list) 18 zip_c = [] 19 for c in zip_list: 20 tuple_to_list = list(c) 21 for i in range(2): 22 if len(tuple_to_list[i]) < max_len: 23 byte_num = max_len-len(c[i]) 24 tuple_to_list[i] = ‘0‘ * byte_num + str(tuple_to_list[i]) 25 zip_c.append(tuple_to_list) 26 for new_c in zip_c: 27 for j in range(max_len): 28 if new_c[0][j] != new_c[1][j]: 29 count = count+1 30 return count
更简便如下:
def totalHammingDistance(self, nums): return sum(b.count(‘0‘) * b.count(‘1‘) for b in zip(*map(‘{:032b}‘.format, nums)))
以上是关于Total Hamming Distance的主要内容,如果未能解决你的问题,请参考以下文章
477. Total Hamming Distance - Medium