def count_m_recursive(sentence):
s = len(sentence)
if s == 0:
return 0
elif sentence[0] == 'm':
return 1
else:
return count_m_recursive(sentence[1:s-1]
这是我的代码。所以如果count_m_recursive('my oh my')
我应该得到2
代码有什么问题?
答案 0 :(得分:20)
有两件事是错的:
您正在切断每次递归调用的 last 字符:
return count_m_recursive(sentence[1:s-1])
请勿将通话限制为s-1
,结束指数不。
当您在开始时找到m
时,您不想忽略文本的其余部分;您的版本返回1
而会忽略字符串的其余部分。
您的功能适用于:
elif sentence[0] == 'm':
return 1 + count_m_recursive(sentence[1:])
else:
return count_m_recursive(sentence[1:])
或简化:
def count_m_recursive(sentence):
if not sentence: # an empty string tests false
return 0
return (1 if sentence[0] == 'm' else 0) + count_m_recursive(sentence[1:])
甚至使用bool
是int
的子类且True
为1,False
为0的事实:
def count_m_recursive(sentence):
if not sentence: # an empty string tests false
return 0
return (sentence[0] == 'm') + count_m_recursive(sentence[1:])
演示:
>>> def count_m_recursive(sentence):
... if not sentence: # an empty string tests false
... return 0
... return (sentence[0] == 'm') + count_m_recursive(sentence[1:])
...
>>> count_m_recursive('my oh my')
2
答案 1 :(得分:12)
为了好玩,您可以将整个事物写成匿名的lambda表达式,如下所示:
def make_funny_func():
# wrapped the code with return clause to emphasize that it is
# anonymous ;)
return (
# Y combinator
(lambda f: (lambda x: x(x))(lambda y: f(lambda a: y(y)(a))))
# our function wrapped
(lambda count:
lambda s:
# return 1 + f(s[1:]) if the first character is 'm'
# 0 + f(s[1:]) otherwise.
(s[0] == 'm') + count(s[1:])
# but do the thing before only if s is non-empty string
if s
# else return 0
else 0
)
)
count_m_recursive = make_funny_func()
print(count_m_recursive('mmmkay'))
Peer pessure徽章,我们来了; - )
答案 2 :(得分:6)
def count_m_recursive(sentence): #mmmm
if not sentence:
return 0
m_first = 1 if sentence[0] == 'm' else 0
return m_first + count_m_recursive(sentence[1:])
概述当前实施中的一些问题:
False
(例如,如果not s
为空或s
,则None
为真)m
的出现,因此应该有一些count_so_far + recursive_call()
。在您的情况下,因为您检查char char count_so_far
的字符串char是1,如果当前char是m
,否则为0。string[N:]
。 SO 此外,这是tail recursive algorithm的完美示例。这种算法可以表示为循环,具有在一个调用堆栈帧中执行的优点。请注意,许多编译器都会优化尾递归以进行循环(但对于python解释器来说并非如此)。
答案 3 :(得分:1)
问题在于
elif sentence[0] == 'm':
slicing off last char with sentence[1:-1]
//注意布尔值是整数类的派生类
def count_m_recursive(sentence):
return (sentence or 0 ) and ((sentence[0] == 'm') + count_m_recursive(sentence[1:]))