在簿记员中检查双打

仍然是Python的新手,我不得不创建一个函数来检查双精度数,如果找到了双精度数,它应该返回“具有重复数”。因此,我已经正确完成了代码,但是对于为什么它最初发现“薄记员”与下面的代码没有重复之处,我感到更加困惑。


def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

def has_duplicates(string):
    x = histogram(string)
    for b, c in x.items():
        if c > 1:
            return True
        else:
            return False

for string in test_dups:
    if has_duplicates(string):
        print(string, "has duplicates")
    else:
        print(string, "has no duplicates")

输出:

zzz has duplicates
dog has no duplicates
bookkeeper has no duplicates
subdermatoglyphic has no duplicates
subdermatoglyphics has duplicates

这就是我为了使其工作而进行的更改。但是我真的很想理解为什么“簿记员”测试不正确。

def has_duplicates(string):
    x = histogram(string)
    for b, c in x.items():
        if c > 1:
            return True
    else:
        return False
评论
Otto
Otto

Your has_duplicates function returns too soon. Take a look at this for-loop:

for b, c in x.items():
        if c > 1:
            return True
        else:
            return False

Assuming that x is not empty, this for-loop will only have one iteration. This is so, because you only ask the question c > 1 once, and then immediately return either True or False, terminating the for-loop and the function prematurely. Basically, this has the effect of only checking for doubles for the first key-value pair in the dictionary x.

您想让for循环有机会对所有键值对提出相同的问题。当然,一旦找到一对值大于1的键值对,您就拥有了“抢先体验”,无需查看其余的键值对。

点赞
评论