[英]PYTHON: Handling the KeyError
I was trying to solve a problem (checking if string s
and t
are anagram) in Python:我试图在 Python 中解决一个问题(检查字符串s
和t
是否为字谜):
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.由于s
和t
都只包含来自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:我收到以下错误:
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()
是同义词,只是后者在为空时是安全的并返回默认值。 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.