gpt4 book ai didi

python-3.x - Hackerrank Python3 哈希表 : Ransom Note and dictionary comprehension

转载 作者:行者123 更新时间:2023-12-04 09:41:08 27 4
gpt4 key购买 nike

我正在学习 Python,我用它来解决 HackerRank 上的任务。我的练习有问题 Hash Tables: Ransom Note .我已经编写了该代码:

def checkMagazine(magazine, note):
mag_h = {}
#mag_h = {i: mag_h[i] + 1 if i in mag_h else 1 for i in magazine}
for i in magazine:
if i in mag_h:
mag_h[i] += 1
else:
mag_h[i] = 1
for i in note:
if (not i in mag_h) or (mag_h[i] < 1):
print("No")
return
else:
mag_h[i] -= 1
print("Yes")
return

当我使用字典理解(注释行)时,我的代码没有通过所有测试,但是当我使用指令创建字典时,它通过了。不是等价的吗?你能告诉我为什么吗?

对不起我的英语不好 :(

最佳答案

您不能引用您的 dict comp 在其内部分配的变量 - 它不会“迭代地”更新。

很容易证明:

magazine = ["T","T","T","o"]
mag_h = {}
# this references the empty dict mag_h = {} all the time and never finds any key in it
mag_h = {i: mag_h[i] + 1 if i in mag_h else 1 for i in magazine}

print(mag_h)

输出:
{'T': 1, 'o': 1}

相对:
mag_h = {}
for i in magazine:
if i in mag_h:
mag_h[i] += 1
else:
mag_h[i] = 1
print(mag_h)

输出:
{'T': 3, 'o': 1}

您可以使用 collections.Counter 轻松解决此任务。或 collections.defaultdict(int)获得更高的性能然后 for -环形。
from collections import Counter

def checkMagazine(magazine, note):
mag_count = Counter(magazine)
note_count = Counter(note)

return all(occ <= mag_count.get(key,0) for key,occ in note_count.items())

m, n = map(int, input().strip().split())
magazine = input().strip().split()
ransom = input().strip().split()
print("Yes" if checkMagazine(magazine, ransom) else "No")

关于python-3.x - Hackerrank Python3 哈希表 : Ransom Note and dictionary comprehension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62326895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com