-3

in python I am receiving the error

name 'isPalindrome' is not defined

even though I am (I think) clearly defining my function.

class Solution:
    def isPalindrome(s) -> bool:
        if len(s)%2==0:  #even length
            for i in range(0,len(s)/2): 
                if s[i]!=s[len(s)-i]:
                    return false
        else:           #odd length
            for i in range(0,(len(s)-1)/2):
                if s[i]!=s[len(s)-i]:
                    return false     
        return true
    
    def longestPalindrome(self, s: str) -> str:
        longestString = "";
        for i in range(len(s)):
            for j in range(0,len(s)):
                if(isPalindrome(s[i:j])):                 #the error is here
                    if(len(s[i:j]) > len(longestString)):
                        longestString = s[i:j]
                                  
        return longestString
    
    ans = isPalindrome("dad") #this does not give warning 'undefined'

I am proficient in Java, C++, but just starting to learn python3. I am forcing myself to learn it by doing leetcode in Python. Any help would be appreciated

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
aberns
  • 3
  • 1
  • 3
    I'd suggest looking up a tutorial on Python, as you've misunderstood how to use classes in Python. It differs from Java/C++. First of, you must have `self` as first parameter, so your `isPalindrome` is invalid (not really, but it's not doing what you think. Also, you need an instance to call a method. Lastly, you shouldn't have code in your class definition (it can be in the methods or in the global scope, but you very rarely have it in the class scope). – Ted Klein Bergman Sep 20 '21 at 18:00
  • "I am forcing myself to learn it by doing leetcode in Python" Not a good way to learn Python if you goal is to learn the language. leetcode is more general algorithms skills. This is a *great* example why you shouldn't try to *learn* python using leetcode – juanpa.arrivillaga Sep 20 '21 at 18:15
  • That being said, Python is easy to learn. I would start with the [official tutorial](https://docs.python.org/3/tutorial/index.html) and come back to leetcode after you've gone through that (at least through section 9 on classes). – juanpa.arrivillaga Sep 20 '21 at 18:17

1 Answers1

0

The presumption in your question is not appropriate. You can call functions within another functions in python. In python a non-static method of the class also takes self as an argument, which is much like this in C++. The error you are getting is coming from the fact that you are missing this require argument.

Please note that the argument name self is more of a convention than an actual requirement. Also when you call the method, you don't have to provide that argument ecxplicitly.

Gábor Pálovics
  • 455
  • 4
  • 12