递归计算字符

时间:2014-04-09 09:29:08

标签: python recursion

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

代码有什么问题?

4 个答案:

答案 0 :(得分:20)

有两件事是错的:

  1. 您正在切断每次递归调用的 last 字符:

    return count_m_recursive(sentence[1:s-1])
    

    请勿将通话限制为s-1,结束指数

  2. 当您在开始时找到m时,您不想忽略文本的其余部分;您的版本返回1会忽略字符串的其余部分

  3. 您的功能适用于:

    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:])
    

    甚至使用boolint的子类且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:])

概述当前实施中的一些问题:

  1. 无需计算字符串的长度以检查字符串是否为空。空字符串相当于布尔“上下文”中的False(例如,如果not s为空或s,则None为真)
  2. 您没有在字符串中总结m的出现,因此应该有一些count_so_far + recursive_call()。在您的情况下,因为您检查char char count_so_far的字符串char是1,如果当前char是m,否则为0。
  3. 正确切片以获得除前N个字符之外的所有字符串string[N:]。 SO
  4. 上有一个good explanation of slicing

    此外,这是tail recursive algorithm的完美示例。这种算法可以表示为循环,具有在一个调用堆栈帧中执行的优点。请注意,许多编译器都会优化尾递归以进行循环(但对于python解释器来说并非如此)。

答案 3 :(得分:1)

问题在于

  1. elif sentence[0] == 'm':
  2. slicing off last char with sentence[1:-1]
  3. //注意布尔值是整数类的派生类

    def count_m_recursive(sentence):
        return (sentence or 0 ) and ((sentence[0] == 'm') + count_m_recursive(sentence[1:]))