简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM