python-3.x - NameError on a function while calling for it in another function of a class
问题描述
I developed some code for a problem on leetcode.com. There was a class and a function and I added another function matchingBrackets
. Yet, when I make the code run I have a NameError on this function. Indeed, it seems it is not defined.
class Solution:
def matchingBrackets(self, s:str) -> bool:
lefts = ['(','{','[']
rights = [')',']','}']
if s[0] in lefts:
function(s[1:],type)
elif s[0] in rights:
if s[0] == bracket:
return True
else:
return False
else:
print("different from brackets")
s = s[1:]
def isValid(self, s: str) -> bool:
return matchingBrackets(s[1:],bracket)
When running it the code on leetcode console, it returns:
NameError: name 'matchingBrackets' is not defined
Line 19 in isValid (Solution.py)
Line 30 in __helper__ (Solution.py)
Line 44 in _driver (Solution.py)
Line 55 in <module> (Solution.py)
解决方案
我认为有几个问题。
当您提到在同一个类中定义的方法时def method(self, arg1, arg2):
,您需要进一步使用该方法,就self.method(arg1, arg2)
好像您在同一个类中使用它一样。也就是说,您的isValid
方法需要返回self.matchingBrackets(s[1:],bracket)
。
此外,您定义matchingBrackets
为一种方法,除了 之外仅采用一个参数self
,但随后您将两个参数传递给它s[1:]
和bracket
。这也是为什么不清楚变量bracket
指的是什么的原因。
另外,我真的不明白function(s[1:],type)
指的是什么。它是否在您发布的代码片段之外定义了它?
最后,我不确定该函数的逻辑是否符合 Leetcode 问题的要求。
推荐阅读
- html - 浮动右元素反转
- raspberry-pi - 使用 USB 电缆或 USB 串行连接两个树莓派
- sas - 使用索引变量的唯一值创建数据集
- ruby - 使用 Webrick 在所有接口上公开端口
- sql - 在 Oracle 中使用 SQL 查找带有意外字符的电话号码?
- arrays - 在swift 4中查找一个数组[(String,Bool)]是否包含来自Array2 [String]的任何字符串
- javascript - 从具有动态键的对象列表中取最小的数字
- javascript - 当用户单击按钮时向下滚动到特定的 div
- selenium - 测试是否可以抛出任何异常以立即结束测试/告诉 TestNG“停止运行此测试”并报告成功而不是忽略?
- flutter - 如何阻止 GridView 中的文本溢出