作为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
您的
has_duplicates
函数返回得太快。看看这个for循环:假设
x
不是空的,这个for循环将只有一次迭代。这是因为您只询问问题c > 1
一次,然后立即返回True
或False
,过早终止for循环和函数。基本上,这只会检查字典x
中第一个键值对的double您希望让for循环有机会对所有键值对提出相同的问题。当然,一旦您找到一个值大于1的键值对,您就有了一个“早出”,不需要查看其余的键值对
相关问题 更多 >
编程相关推荐