You need to make the count variable a function variable, like
def lenRecur(s): lenRecur.count = 0
However, I see some problems with the code.
1) If you try to find the number of alphabets in a string through recursion, this will do:
def lenRecur(s): def leng(s, count = 0): if not s: return count else: count += int(s[0].isalpha()) return leng(s[1:], count) return leng(s)
But still, I would prefer to have one function to complete the task, for example, there will be no leng method at all.
2) If your goal is just to find the number of alphabets in a string, I would prefer a list comprehension
def alphalen(s): return sum([1 for ch in s if ch.isalpha()])
If this is something other than the purpose of the training, I suggest you avoid recursion. Because the solution cannot be used for large strings (say, finding the number of alphabets from the contents of a file). You can hit the height of a RunTimeError with the maximum recursion depth.
Despite the fact that you can get around this by setting the recursion depth through the setrecursionlimit function, I suggest you go the other way. Read more about setting recursionlimit here .
thiruvenkadam
source share