从递归函数返回堆栈变量的最佳方法是什么?

时间:2016-05-23 21:58:25

标签: python recursion

我有一种情况需要返回列表中的第一个项目,当我使用递归时如何返回它?:

def get_hostname (ifname):
    try :
        # Do something to get hostname
        return hostname
    except IOError:
        return -1


def get_hostname_r(lst):
    if not lst:
        return False
    if get_hostname(lst[0]) != -1 :
        print 'Found ', get_hostname(lst[0])
        return get_hostname(lst[0]) # DOESNT WORK
    else :
        print 'Not found ', get_hostname(lst[0])
        get_hostname_r(lst[1:])

print 'return = ', get_hostname_r(['eth1','eth2','eth3','eth4','eth5' ]) 

我知道返回会返回到调用堆栈但是Iam在这里寻找最佳实践而不使用全局变量来获取值?

2 个答案:

答案 0 :(得分:2)

您可以简单地返回值,返回的值将移交整个递归堆栈:

def get_hostname_r(lst):
    if not lst:
        return False
    if get_hostname(lst[0]) != -1 :
        print 'Found ', get_hostname(lst[0])
        return get_hostname(lst[0])
    else:
        print 'Not found ', get_hostname(lst[0])
        return get_hostname_r(lst[1:])

但更易于阅读的是for循环:

def get_hostname_r(interfaces):
    for interface in interfaces:
        result = get_hostname(interface)
        if result != -1:
            return result
    return False

答案 1 :(得分:0)

首先,如果你不能对IO错误做任何事情,不要通过返回-1来掩盖它(" -1是什么意思?为什么我没有得到一个?主持人回来了?")。只记录get_hostname可能引发IOError。

def get_hostname(ifname):
    # Do stuff that might raise an IOError
    return hostname

递归版本也是如此。要么返回有效的主机名,要么引发异常(或者让未被捕获的异常继续)。

def get_hostname_r(lst):
    if not lst:
        raise IOError("Hostname not found")

    try:
        hostname = get_hostname(lst[0])
        print >>sys.stderr, 'Found {0}'.format(hostname)
        return hostname
    except IOError:
        print 'Not found with {0}'.format(lst[0])
        return get_hostname_r(lst[1:])

当然,递归并不是写这个的最佳方式;使用简单的for循环来迭代lst

def get_hostname_iter(lst):
    for ifname in lst:
        try:
            return get_hostname(ifname)
        except IOError:
            continue
    raise IOError("Hostname not found")
相关问题