Exercism: Hamming (Python)
简单版的汉明距离计算。开始写了一个循环单个比,mentor回复说用列表解析比较简单。
原版
def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise ValueError("The length of string a and b are not same")
distance = 0
for i in range(len(strand_a)):
if strand_a[i] != strand_b[i]:
distance += 1
return distance
改进版
def distance(strand_a, strand_b): if len(strand_a) != len(strand_b): raise ValueError("The length of string a and b are not same") return sum(1 if strand_a[i] != strand_b[i] else 0 for i in range(len(strand_a)))
评论
发表评论