-1

我想知道标题中说了什么。例如,如何计算递归循环并最终返回或打印结果。

这是我的代码,但它不能正常工作:

def lenRecur(aStr):
    number = 0
    print "lenRecur number is ", number
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    if aStr == '':
        return 0
    else:
        print aStr
        number += 1
        print "else number is ", number
        return lenRecur(aStr[:-1])

好的,所以当我写作时,我再次测试并且它可以工作,如果我使用 lenRecur("word", 0) 并且还自定义我的代码它可以工作。问题是,这是不合法的。这是不合法的,我不允许这样做:(

所以自定义代码:

def lenRecur(aStr, number):
    print "lenRecur number is ", number
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    if aStr == '':
        return number
    else:
        print aStr
        number += 1
        print "else number is ", number
        return lenRecur(aStr[:-1], number)
4

3 回答 3

1

我认为递归版本len远非最有效的,但如果你想这样做,你应该使用辅助函数来隐藏第二个参数:

def lenRecur(aStr):
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    # place the doc string next to the `def`
    # the outside world has no ability to accidentally set the parameter
    def lenRecurHelper(aStr, num = 0):
        print "lenRecur number is ", number

        # empty strings are falsy, so just test for that.
        if not aStr:
            return num
        print aStr
        lenRecurHelper(aStr[:-1],num + 1)

    return lenRecurHelper(aStr)
于 2013-01-17T00:25:30.363 回答
1

如果我理解正确,这应该可以解决您的问题:

def lenR(s,n=0):
    if s:
        return lenR(s[:-1],n+1)
    else:
        return n

#testing it:
lenR('this code is not pretty')  # output: 23
lenR('egg')   # output: 3
lenR('spam')  # output: 4

它不漂亮,但是通过递归计算字符串的长度也不漂亮。

于 2013-01-17T01:04:06.077 回答
-1

我相信您的意图是number用作静态函数变量。这可以通过以下方式实现:

def lenRecur(aStr):
    if not hasattr(lenRecur, 'number'):
        lenRecur.number = 0
    print "lenRecur number is ", lenRecur.number
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    if aStr == '':
        return 0
    else:
        print aStr
        lenRecur.number += 1
        print "else number is ", lenRecur.number
        return lenRecur(aStr[:-1])

每次重置计数器的替代方法,代价是使用两个参数:

def lenRecur(aStr, recurse=False):
    if not recurse:
        lenRecur.number = 0
    print "lenRecur number is ", lenRecur.number
    '''
    aStr: a string

    returns: int, the length of aStr
    '''
    if aStr == '':
        return 0
    else:
        print aStr
        lenRecur.number += 1
        print "else number is ", lenRecur.number
        return lenRecur(aStr[:-1], True)

我不知道练习的实际意义是什么,以及在实施中可以做什么和不能做什么。

于 2013-01-17T00:10:22.110 回答