从'if'语句而不是'else'语句返回结果的递归函数

时间:2015-08-03 12:22:50

标签: python-3.x recursion

我是Python的新手,我正在尝试编写一个简单的递归函数:

def bugged_recursion(inp_value,list_index=0):
    '''Define a recursive function that tag lists according to one parameter.
    '''
    #check if a criterion is true at position 0 in the list
    if list_index == 0:
        if inp_value[list_index] == 'valid':
            status = 'valid inp_value'
        #if the criterion is false call the function at the next index
        else:
            status = 'invalid inp'
            list_index +=1
            bugged_recursion(inp_value,list_index=list_index)
    #check if a criterion is true at position 1 in the list
    else:
        if inp_value[list_index] == 'valid':
            status = 'index {} is a valid inp_value'.format(list_index)
        else:
            status = 'index is never a valid inp_value'
    print(status)
    #return the input and its status
    return (inp_value,status)

if __name__ == '__main__':
    inp_value = ['invalid','invalid']
    bugged_recursion(inp_value)

我不明白为什么这个函数从if语句返回状态,而不是返回最后一个else语句中包含的状态。 对我来说,最奇怪的是它在某些时候打印出正确的状态但不会返回它。

我无法理解为什么......我真的很好奇如何使用递归函数执行此任务。

1 个答案:

答案 0 :(得分:0)

哇哇,这是多么折磨。

def bugged_recursion(inp_value, list_index=0):
    # i don't get why you compare list_index here
    if list_index == 0:
        # you'll get an IndexError if list_index > len(inp_value)
        if inp_value[list_index] == 'valid':
            status = 'valid inp_value'
        else:
            status = 'invalid inp'
            # there is only one place where you increment list_index
            # i suppose there is something wrong here
            list_index +=1
            # you forgot to return here
            return bugged_recursion(inp_value, list_index=list_index)
    else:
        if inp_value[list_index] == 'valid':
            status = 'index {} is a valid inp_value'.format(list_index)
        else:
            status = 'index is never a valid inp_value'
    return (inp_value,status)

除此之外,人们通常倾向于尽可能避免recursion(例如在Dive into Python上)。

这是否满足您的需求?

def no_recursion(inp_value):
    for i, val in enumerate(inp_value):
        # you probably have a good reason to test the index
        if i == 0:
            if val == 'valid':
                yield 'valid inp_value: %s' % val
            else:
                yield 'invalid inp: %s' % val
        else:
            yield 'index %s is %s valid inp_value' % (
                i,
                'a' if val == 'valid' else 'never'
            )

print tuple(no_recursion(inp_value))

给予:('invalid inp: invalid', 'index 1 is never valid inp_value')