python如何在多次递归找到答案后停止接下去的递归
PHP中文网
PHP中文网 2017-04-17 15:35:28
0
5
921
def foo(a):
    if 得到了结果:
        结束递归
        显示
    if 错误:
        return
    else:
        for each in *****:
            foo(each)

这是我大概的思路,试过用exit()虽然停了但会报错

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
Ty80

After displaying, return a special value and then check the return variable of foo. If it is that special value, it is directly based on the return value

大家讲道理

For problems that are too vague, you can only analyze them through the code.

PHPzhong

Recursion requires exit conditions, which is what you call stopping. .

Generally, a branch judgment is required inside recursion, such as:

def fab(n):
  if n<2:
    return 1
  else
    return fab(n-1)+fab(n-2)

After recursing a certain number of times and reaching the above if condition, the recursion ends.

Peter_Zhu

Just add a return after displaying

PHPzhong
需要有退出条件, 比如检查一段数据中是否有unicode字符
def check_unicode(data):
    """
    :param data:
    :return:
    """
    if isinstance(data, dict):
        for k, v in data.iteritems():
            if isinstance(v, dict):
                if check_unicode(v):
                    return True
            elif isinstance(v, list):
                if check_unicode(v):    # 检查为True退出
                    return True
            else:
                if v and isinstance(v, unicode):
                    return True
    elif isinstance(data, list):
        for v in data:
            if isinstance(v, dict):
                if check_unicode(v):
                    return True
            elif isinstance(v, list):
                if check_unicode(v):
                    return True
            else:
                if v and isinstance(v, unicode):
                    return True
    else:
        if data and isinstance(data, unicode):
            return True
    return False
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template