[英]recursively counting number of times an object occurs in a string
因此,我需要计算给定值在字符串中出现的次数,例如“ hello world”,“ o”,但是我的最大深度已被超出...我也不应该递归地执行此操作
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)
我主要是
print(count('hello world' , 'o'))
if
和else
导致另一个递归调用,这意味着该函数无法停止自身的调用。 这是程序员学习递归的一个非常普遍的错误。
你的功能需要一定的条件下它不会进一步调用本身,而只是返回一些值,以防止无限递归。 也许如果字符串为空,则可以返回零。
就像其他人所说的那样,使它成为递归函数实际上没有任何好处,除非是作为学习练习。 一个简单的循环会更好,而使用内置字符串.count()
函数仍然会更好。
根据此答案,您正在寻找str.count()
无需使您自己的函数已经内置! 谢谢Python <3
print('hello world'.count('o'))
#2
您将需要在保持计数的同时循环浏览字母。
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'))
使用python的内置函数'count'
sentence = "Hello world!"
sentence.count('o')
那会给你结果。
您的基本情况是不正确的,因为如果len(s) == 1 and s != token
您将再次递归,但条件是len(s) == 0
,而您没有终止条件。
因此, 无论何时len(s) <= 1
您都需要终止。 您还需要合并递归调用的结果。
固定版本可能类似于以下内容:
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
尽管许多答案都解决了代码中的缺陷,但我认为他们的示例解决方案并不符合您要实现的目标。 您拥有大部分零件,但我会:选择单点收益; 由于您标记了此[python-3.x],因此请充分利用Python 3语法; 考虑一下这是一个通用序列,而不是一个字符串:
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
用法
>>> print(count('hello world', 'o'))
2
>>> print(count(['e', 'l', 'e', 'p', 'h', 'a', 'n', 't'], 'e'))
2
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.