【问题标题】:PYTHON: Handling the KeyErrorPYTHON:处理 KeyError
【发布时间】:2020-12-23 14:49:56
【问题描述】:

我试图在 Python 中解决一个问题(检查字符串 st 是否为字谜):

算法: 要检查t 是否是s 的重新排列,我们可以计算两个字符串中每个字母的出现次数并进行比较。由于st 都只包含来自a-z 的字母,所以一个大小为26 的简单计数器table 就足够了。

我们可以为s 中的每个字母递增计数器,并为t 中的每个字母递减计数器,然后检查计数器是否回到零。

代码:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        
        if len(s) != len(t): 
            return False
        
        table = {} 
        
        for i in range(len(s)):
            table[s[i]] = table.get(table[s[i]], 0) + 1
            
        for i in range(len(t)):
            table[t[i]] = table.get(table[s[i]], 0) - 1
            if table[t[i]] < 0:
                return False
            
        return True

然而,我在第一个循环中得到一个 KeyError。为了解决这个问题,我尝试使用.get(),但仍然无法解决。

我收到以下错误:

【问题讨论】:

  • 您需要准确地告诉我们您遇到了什么错误。什么是回溯?
  • 另外,table 是什么?请edit 包含minimal reproducible example
  • table[s[i]] = table.get(table[s[i]], ...) 您正在尝试访问table 中的密钥,您正在那里进行设置,而table 无论如何此时都是空的……
  • table[s[i]] = table.get(s[i], 0) + 1?
  • @deadshot 是的,谢谢。这修复了错误。但是,代码似乎没有正确解决问题:)

标签: python keyerror anagram


【解决方案1】:
  • dict 中查找值时,您查找了两次:table.get(table[s[i]], 0)
  • [].get() 是同义词,除了后者空时安全并返回默认值。
  • 这应该是您需要的循环。感谢@deadshot。
        for i in range(len(s)):
            table[s[i]] = table.get(s[i], 0) + 1
            
        for i in range(len(t)):
            table[t[i]] = table.get(t[i], 0) - 1
            if table[t[i]] < 0:
                return False

【讨论】:

  • 谢谢。此外,return False if len(s) != len(t) else sorted(s) == sorter(t) 有效。我只是想修复上述代码:)
  • 知道了。是的,我看到 dict 查找有@deadshot 提到的问题。
猜你喜欢
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 2011-07-02
  • 2012-11-16
  • 2014-04-10
  • 2017-12-08
  • 1970-01-01
相关资源
最近更新 更多