Sriram Narra
Sriram Narra

Reputation: 19

How to we write a recursive function call in python

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)

Upvotes: 0

Views: 102

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236150

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.

Upvotes: 2

Related Questions