简体   繁体   English

PYTHON:处理 KeyError

[英]PYTHON: Handling the KeyError

I was trying to solve a problem (checking if string s and t are anagram) in Python:我试图在 Python 中解决一个问题(检查字符串st是否为字谜):

Algorithm: To examine if t is a rearrangement of s , we can count occurrences of each letter in the two strings and compare them.算法:要检查t是否是s的重排,我们可以计算两个字符串中每个字母的出现次数并进行比较。 Since both s and t contain only letters from az , a simple counter table of size 26 is sufficient.由于st都只包含来自az字母,因此大小为 26 的简单计数器table就足够了。

We could increment the counter for each letter in s and decrement the counter for each letter in t , then check if the counter reaches back to zero.我们可以为s每个字母递增计数器,并为t每个字母递减计数器,然后检查计数器是否回到零。

Code:代码:

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

Yet, I get a KeyError in the first loop.然而,我在第一个循环中得到了一个 KeyError 。 To handle that, I tried using .get() but still cannot tackle.为了解决这个问题,我尝试使用.get()但仍然无法解决。

I am getting the following error:我收到以下错误:

在此处输入图片说明

  • While looking for value in dict , you lookup twice: table.get(table[s[i]], 0) .dict查找值时,您查找了两次: table.get(table[s[i]], 0)
  • [] and .get() are synonymous except that latter is safe when empty and returns default. [].get()是同义词,只是后者在为空时安全的并返回默认值。
  • This should be the loop you'd need.这应该是您需要的循环。 Credits to @deadshot.归功于@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM