Py学习  »  Python

在python中的两个哈希映射中查找不匹配的键值的计数

pari • 3 年前 • 1394 次点击  

我比较了两个字符串,并计算了一个字符串可以是另一个字符串的字谜的步数,我对一个字符串使用了两个哈希映射。然后我比较两个散列映射之间的差异,计算差异。请帮助我们计算这样的差异!

s="leetcode"
t= "coats"

以下是我的代码:

 def minSteps(self, s: str, t: str) -> int:
    map_s = {}
    map_t = {}
    for i in range(len(s)):
        if s[i] not in map_s:
            map_s[s[i]] = 0
        map_s[s[i]] += 1
    for i in range(len(t)):
        if t[i] not in map_t:
            map_t[t[i]] = 0
        map_t[t[i]] += 1
    print(map_t)
    print(map_s)
    for key, val in map_s.items():
        if val != map_t[key]: 
            count += 1
    return count

当我打印两个HashMap时,我得到的结果是,如果计算两个HashMap之间的差异,预期的差异是7。

   {'c': 1, 'o': 1, 'a': 1, 't': 1, 's': 1}
   {'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1}

这里有一个类似的问题。 Comparing two dictionaries and checking how many (key, value) pairs are equal .然而,我找不到我要找的东西。请帮忙!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130563
 
1394 次点击  
文章 [ 1 ]  |  最新文章 3 年前