Reputation: 97
So I am needing to count the number of times a given value occurs in a string, such as "hello world" , "o", however my maximum depth is getting exceeded...I should aslo not I would like to do this recursively
def count(s, token) : #OUT OF RANGE
if len(s) == 1 and s[0] == token :
return 1 + count(s[1:], token)
#return s[0]
else :
return count(s[1:],token)
in main I have
print(count('hello world' , 'o'))
Upvotes: 0
Views: 403
Reputation: 41872
Although many of the answers address the flaw in your code, I don't feel their example solutions are in the spirit of what you're trying to achieve. You have most the parts and pieces but I would: opt for a single point of return; take advantage of Python 3 syntax since you tagged this [python-3.x]; think of this a generic sequence rather than specifically a string:
def count(sequence, token):
token_count = 0
if sequence:
head, *tail = sequence
if head == token:
token_count += 1
token_count += count(tail, token)
return token_count
USAGE
>>> print(count('hello world', 'o'))
2
>>> print(count(['e', 'l', 'e', 'p', 'h', 'a', 'n', 't'], 'e'))
2
>>>
Upvotes: 0
Reputation: 33335
Both the if
and the else
lead to another recursive call, meaning there is no way for the function to stop calling itself. This is a very common mistake for programmers learning about recursion.
Your function needs some condition where it does not further call itself, but simply returns some value, to prevent infinite recursion. Perhaps if the string is empty, you could return zero.
As others have said, there's really no benefit in making this a recursive function, except as a learning exercise. A simple loop would be better, and using the built-in string .count()
function is better still.
Upvotes: 1
Reputation: 12990
Your base case is incorrect because if len(s) == 1 and s != token
you'll recurse again but with the condition len(s) == 0
for which you don't have a terminating condition.
So you need to terminate no matter what when len(s) <= 1
. You also need to combine the results of your recursive calls.
A fixed version can look something like the followin:
def count(s, token):
if len(s) <= 1:
return 1 if s == token else 0
return count(s[0], token) + count(s[1:], token)
print(count('hello world' , 'o')) # 2
Upvotes: 0
Reputation: 475
Use python's built-in function 'count'
sentence = "Hello world!"
sentence.count('o')
That will give you the result.
Upvotes: 0
Reputation: 273
You will want to loop though the letters while keeping a count.
def count(s, token) : #OUT OF RANGE
count = 0
for i in range(len(s)):
if s[i] == token : count += 1
return count
print(count('Hello, World' , 'o'))
Upvotes: 0
Reputation: 27495
As per this answer you're looking for str.count()
no need to make you're own function it's already builtin! Thanks Python <3
print('hello world'.count('o'))
#2
Upvotes: 0