在python中查找两个hashmap中不匹配的键、值的数量

发布于 2025-01-10 10:28:37 字数 998 浏览 0 评论 0原文

我正在比较两个字符串,并计算一个字符串可以是另一个字符串的字谜词的步骤,其中我对一个字符串使用两个哈希图。然后我比较两个哈希图之间的差异作为计数差异。请帮忙计算这样的差异!

例如,

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

当我打印两个哈希图时,这就是我得到的结果,计算两者之间的差异后,预期差异为 7。

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

这是一个类似的问题。 比较两个字典和检查有多少(键,值)对相等。但是,我找不到我要找的东西。请帮忙!

I am comparing two strings and counting in how many steps one string can be an anagram of another for which I use two hashmaps each for one string. Then I compare the difference between two hash maps as count the difference. Please help on how to count such a difference!

For example,

s="leetcode"
t= "coats"

Following is my code:

 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

When I print both hashmaps, this is what I get and the expected difference is 7 counting the difference between two.

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

Here is a similar question. Comparing two dictionaries and checking how many (key, value) pairs are equal . However, I could not find what I am looking for. Please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一个人的夜不怕黑 2025-01-17 10:28:37

如果您想对事物进行计数,请考虑使用计数器
它们也可以相加和相减,所以你可以做一些事情
像这样:

from collections import Counter

def minSteps(s: str, t: str) -> int:
    cs = Counter(s)
    ct = Counter(t)
    diff = (cs - ct) + (ct - cs)
    return sum(diff.values())

If you want to count things, consider using a Counter.
They can also be added and subtracted, so you could do something
like this:

from collections import Counter

def minSteps(s: str, t: str) -> int:
    cs = Counter(s)
    ct = Counter(t)
    diff = (cs - ct) + (ct - cs)
    return sum(diff.values())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文