检查簿记员是否有替身

2024-05-15 06:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

作为Python新手,我必须创建一个检查double的函数,如果找到double,它应该返回“hasdeplicates”。因此,我已经正确地完成了代码,但我更困惑的是,为什么它最初发现“簿记员”与下面的代码没有重复项


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

Tags: no代码inforstringreturnifdef
1条回答
网友
1楼 · 发布于 2024-05-15 06:19:12

您的has_duplicates函数返回得太快。看看这个for循环:

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

假设x不是空的,这个for循环将只有一次迭代。这是因为您只询问问题c > 1一次,然后立即返回TrueFalse,过早终止for循环和函数。基本上,这只会检查字典x中第一个键值对的double

您希望让for循环有机会对所有键值对提出相同的问题。当然,一旦您找到一个值大于1的键值对,您就有了一个“早出”,不需要查看其余的键值对

相关问题 更多 >

    热门问题