search

Home  >  Q&A  >  body text

python如何在多次递归找到答案后停止接下去的递归

def foo(a):
    if 得到了结果:
        结束递归
        显示
    if 错误:
        return
    else:
        for each in *****:
            foo(each)

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

PHP中文网PHP中文网2803 days ago903

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:37:28

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 15:37:28

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

    reply
    0
  • PHPz

    PHPz2017-04-17 15:37:28

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:37:28

    Just add a return after displaying

    reply
    0
  • PHPz

    PHPz2017-04-17 15:37:28

    需要有退出条件, 比如检查一段数据中是否有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

    reply
    0
  • Cancelreply