用于回文排列的Python输出打印问题

问题描述 投票:0回答:1

我想看看给定的字符串是否是回文的排列。这是python解决方案。我正在尝试针对以下输入示例进行测试,但出现错误。

import re
class Solution(object):
    def isPalindrome(self, s):

        regex = re.compile('[^a-zA-Z0-9]')
        s=regex.sub('', lower(s))
        print(s)
        j=len(s)-1
        for i in range(0,len(s)/2):
            if s[i]==s[j]:
                j-=1
            else:
                return False

        return True

    # The word is civic , which is a palindrome. So it should return true.    
    s = "vicic"

print(isPalindrome(s))

我收到此错误:“ NameError:未定义名称'self'”。如何解决并打印输出?

python algorithm debugging data-structures
1个回答
0
投票

isPalindrome(),如您在此处定义的,与对象/类Solution相关联。

与常规的Python函数不同,您的方法在解决方案对象上被调用。

如果要在给定当前结构的情况下调用它,则必须首先实例化解决方案的实例,创建要测试的字符串,然后在该对象上调用该方法:

sol = Solution() # instance of Solution
s = "vicic"
sol.isPalindrome(s) # False

还请注意,由于错误的范围,我从先前声明的位置取出了字符串s

通常来说,您的解决方案类似乎有点矫kill过正,Python的优点之一在于它具有编写简单脚本的能力,因此您可以将isPalindrome()重写为普通函数而不是方法。

© www.soinside.com 2019 - 2024. All rights reserved.