繁体   English   中英

我想了解递归过程吗?

[英]I'm trying to understand the recursion process?

houses = ["Shaah's house", "Joseph's house", "Kyle's house", "Stan's house"]

def deliver_presents_recursively(houses):
    # Worker elf doing his work
    if len(houses) == 1:
        house = houses[0]
        print("Delivering presents to", house)
    else:
        mid = len(houses) // 2
        first_half = houses[:mid]
        second_half = houses[mid:]

        # Divides his work among two elves
        deliver_presents_recursively(first_half)
        deliver_presents_recursively(second_half)

delivery_presents_recursively(房屋)

递归很难理解,但它的工作原理就像魔术。

在您的示例中, deliver_presents_recursively的任务是将礼物递送到所提供的每个房屋。 怎么样? 好吧,很明显,一个人一次只能将礼物递送到一所房子,因此, deliver_presents_recursively试图简化问题。

如果仅提供一所房子( if len(houses) == 1: deliver_presents_recursively ,则deliver_presents_recursively交付礼物并退出(嗯,实际上返回到调用函数)。

如果提供的房屋不止一个,它会将清单分为两半,然后尝试交付给上半部分,然后再交付给下半部分。 由于deliver_presents_recursively可以容纳任意数量的房屋,因此您可以重复使用该功能来尝试交付这两组较小的房屋。

递归需要一个对它自己的调用,通常需要使用一个简化的参数集来进行调用(也就是说,您不希望使用具有相同参数的函数来调用该函数,否则它将永远不会结束!)

递归还需要终止符,例如len(houses) == 1 就是说,它不会再次调用自己的情况。

在这种特殊情况下,使用简单的迭代可能是有意义的,例如:

def deliver_presents_non_recursively(houses):
    for house in houses:
        print ("Delivering presents to", house)

但是您就不会尝试递归了。

另一个简单的递归示例是阶乘(8!等于8 * 7 * 6 * 5 ...)。 这样想:

What is 8 factorial? 
- it's 8 * 7 factorial
  What is 7 factorial?
  - it's 7 * 6 factorial
    What is 6 factorial?
    - it's 6 * 5 factorial
      What is 5 factorial?
      - it's 5 * 4 factorial
        What is 4 factorial?
        - it's 4 * 3 factorial
          What is 3 factorial?
          - it's 3 * 2 factorial
            What is 2 factorial?
            - it's 2 * 1 factorial
              What is 1 factorial?
              - it's 1
              therefore 2 * 1
            therefore 3 * 2
          therefore 4 * 6
        therefore 5 * 24
      therefore 6 * 120
    therefore 7 * 720
  therefore 8 * 5040
therefore 40320

查看每个实例如何比前一个“小”,直到达到终止点(1阶乘),然后结果渗透回去。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM