Python 3.x Hackerrank Python3哈希表:赎金注释和字典理解
我正在学习Python,我用它来解决HackerRank上的任务。我对运动有问题。我已经编写了以下代码:Python 3.x Hackerrank Python3哈希表:赎金注释和字典理解,python-3.x,dictionary,Python 3.x,Dictionary,我正在学习Python,我用它来解决HackerRank上的任务。我对运动有问题。我已经编写了以下代码: 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
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
def检查刀库(刀库,注释):
mag_h={}
#mag_h={i:mag_h[i]+1如果我在mag_h中,则为我在mag_h中}
对于我在杂志:
如果我在mag_h:
mag_h[i]+=1
其他:
mag_h[i]=1
就我而言,请注意:
如果(不在mag_h中的i)或(mag_h[i]<1):
打印(“否”)
返回
其他:
mag_h[i]=1
打印(“是”)
返回
当我使用字典理解(注释行)时,我的代码不会通过所有测试,但当我使用for指令创建字典时,它会通过。这不是等价的吗?你能告诉我为什么吗
对不起,我的英语是:(您不能引用您的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}
{'T': 3, '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': 1, 'o': 1}
{'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")
从集合导入计数器
def检查刀库(刀库,注释):
刀库计数=计数器(刀库)
注\计数=计数器(注)
返回全部(occ)