【发布时间】:2018-02-10 08:51:57
【问题描述】:
我正在做一个简单的任务:在 Python 中查找两个数组的交集。
我写了代码:
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
hash_2 = {}
for x in nums2:
if x in hash_2:
hash_2[x] = 1
else:
hash_2[x] = hash_2[x] + 1
intersection = []
for x in nums1:
if x in hash_2:
if hash_2[x] >0:
intersection.append(x)
hash_2[x] = hash_2[x] - 1
return intersection
print(intersect([],[1]))
我明白了:
line 14, in intersect
hash_2[x] = hash_2[x] + 1
KeyError: 1
我尝试调试但没有帮助。为什么python程序在字典本身为空时向else条件发送1?
这是 Python 字典中不应该在空字典中搜索的问题吗?
【问题讨论】:
-
这看起来像是
collections.Counter()的作品。
标签: python arrays algorithm dictionary data-structures