0

I have a function "lengthOfLongestSubstring" as in the below code and need to recursively call the function with substring of "s"(For example s[3:]) How do I call it?

I have tried calling recursively like this: lengthOfLongestSubstring(s[1:])

But its popping up an error that "NameError: name 'lengthOfLongestSubstring' is not defined"

    class Solution:
        def lengthOfLongestSubstring(self, s: 'str') -> 'int':
            count = 0
            list1 = []
            for i in range(len(s)):            
                if s[i] not in list1:
                    list1.append(s[i])
                    count= count+1
                    print (list1)
                else:
                    substr = s[i:]
                    if (count < lengthOfLongestSubstring(substr)):
                       count = lengthOfLongestSubstring(substr)
                    break
            return (count)

Expected the recursive call of the function but getting the below mentioned error:

NameError: name 'lengthOfLongestSubstring' is not defined
Line 15 in lengthOfLongestSubstring (Solution.py)
Line 29 in __helper__ (Solution.py)
Line 60 in _driver (Solution.py)
Line 73 in <module> (Solution.py)
3
  • Have given the code in Question. Could you refer that. Commented Feb 15, 2019 at 21:00
  • 2
    Well, how do you call methods of a class inside a method of said class? This problem doesn't have anything to do with recursion at this point Commented Feb 15, 2019 at 21:00
  • remove the class definition and it will work. Commented Feb 15, 2019 at 21:02

1 Answer 1

2

Your lengthOfLongestSubstring is a method inside a class, so you have to call it like this:

self.lengthOfLongestSubstring(substr)

I don't really see the need to define it inside a class, I'd rather extract the whole thing out of it, and then you can invoke it normally. Just delete the line with class Solution on it and indent everything one tab to the left.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.