我知道错误了
"NameError:未定义名称'is_palindrome‘“
我在一个网站上发现了这个简单的问题,它要求创建一个名为Palindrome的类,并在其中创建一个名为is_palindrome的函数来检查给定的单词,如果它是回文和False,则返回True,否则应该使用一个类和一个静态方法(所以我不能删除它们),代码如下所示。
class Palindrome:
@staticmethod
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])
word = input()
print(Palindrome.is_palindrome(word))我已经通过删除类声明来解决这个问题,其他方法如
return word==word[::-1]但是,我试图理解上述代码的问题,为什么当我将它包含在类中时,我会得到这个错误。
"NameError:未定义名称'is_palindrome‘“
发布于 2019-03-26 11:15:56
虽然,我不认为类中的方法或作为静态的方法有什么帮助,但是下面是修复方法:
class Palindrome:
@staticmethod
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and Palindrome.is_palindrome(s[1:-1])
word = input("Enter your word: ")
print(Palindrome.is_palindrome(word))输出
Enter your word: ROTAVATOR
True编辑
如果你不想在课堂上纠缠不清,假设你已经没有别的事情做了:
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])
word = input("Enter your word: ")
print(is_palindrome(word))编辑3
另一种方式是:
class Palindrome:
def is_palindrome(self, s):
return len(s) < 2 or s[0] == s[-1] and self.is_palindrome(s[1:-1])
word = input("Enter your word: ")
p_Obj = Palindrome()
print(p_Obj.is_palindrome(word))发布于 2019-03-26 11:19:12
不用上回文课。只是有
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])https://stackoverflow.com/questions/55355751
复制相似问题