在python中查找两个hashmap中不匹配的键、值的数量
我正在比较两个字符串,并计算一个字符串可以是另一个字符串的字谜词的步骤,其中我对一个字符串使用两个哈希图。然后我比较两个哈希图之间的差异作为计数差异。请帮忙计算这样的差异!
例如,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想对事物进行计数,请考虑使用计数器。
它们也可以相加和相减,所以你可以做一些事情
像这样:
If you want to count things, consider using a Counter.
They can also be added and subtracted, so you could do something
like this: