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)))

评论

此博客中的热门博文

拜厄练习曲44, 45

拜厄练习曲38, 39