2015-08-03 126 views
0

我在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语句中包含的状态。 对我来说,最奇怪的是它在某个点打印正确的状态,但不会返回它。

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

回答

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')

+0

感谢解释这两个如何纠正我的代码,以及如何写出更好的,非递归函数。我不知道是否有必要返回bugged_recursion() 道歉,如果我似乎天真,但我是一个自学者,我会看看你的链接!感谢您的帮助,我很高兴今天学到了一些东西! –