sql 一张表递归_查看我的递归视觉指南(因为一张图片价值1,000字)

sql 一张表递归

In this article, I will explain recursion (almost) completely with visual representations. I’ll show, rather than explain, how each recursive function call interacts with the entirety of the initial function invocation — in other words, how each piece connects to the whole.

在本文中,我将(几乎)完全用视觉表示来解释递归。 我将展示而不是说明每个递归函数调用如何与整个初始函数调用进行交互,换句话说,每个部分如何与整个函数连接。

A few details:

一些细节:

  • The code is written in Python

    该代码是用Python编写的
  • Blue boxes represent the current scope of the function

    蓝色框代表当前功能范围
  • Connecting lines are what a function returns

    连接线是函数返回的内容

Please use the code as a reference, as I do not go over the running of it in detail.

请使用该代码作为参考,因为我不会详细介绍它的运行。

We’ll look at three problems: finding the Anagrams of a string, Merge Sort, and The Tower of Hanoi. They progressively get a little bit more nuanced, so watch out!

我们将研究三个问题:查找字符串的字谜,合并排序和河内塔。 他们逐渐变得更加细微差别,所以要当心!

I’ll discuss more details of recursion below.

我将在下面讨论递归的更多详细信息。

字谜 (Anagrams)

def anagrams(s):
    if s == "":
        return [s]
    else :
        ans = []
    for w in anagrams(s[1: ]):
        for pos in range(len(w) + 1):
            ans.append(w[: pos] + s[0] + w[pos: ])
    return ans

anagrams("abc")

# returns ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

The above is a good intro to the call stack. Notice how each prior call is awaiting the return value of the recursive call.

上面是调用堆栈的一个很好的介绍。 请注意,每个先前的调用如何等待递归调用的返回值。

Also notice how the variable ans values are all appended during the initial function call (1).

还要注意,在初始函数调用(1)期间,变量ans值是如何全部附加的。

合并排序 (Merge Sort)

def merge(lst1, lst2, lst3):
    i1, i2, i3 = 0, 0, 0
    n1, n2 = len(lst1), len(lst2)
    while i1 < n1 and i2 < n2:
        if lst1[i1] < lst2[i2]:
            lst3[i3] = lst1[i1]
            i1 = i1 + 1
        else:
            lst3[i3] = lst2[i2]
            i2 = i2 + 1
        i3 = i3 + 1
    
    # unequal length of lists? Check both
    while i1 < n1: 
        lst3[i3] = lst1[i1]
        i1 = i1 + 1
        i3 = i3 + 1
    
    while i2 < n2:
        lst3[i3] = lst2[i2]
        i2 = i2 + 1
        i3 = i3 + 1

def mergeSort(nums):
    n = len(nums)
    if n > 1:
        m = n // 2
        nums1, nums2 = nums[:m], nums[m:]
        mergeSort(nums1)
        mergeSort(nums2)
        merge(nums1, nums2,nums)
    
numbers = [7, 4, 6, 2, 8]
mergeSort(numbers)

print(numbers)
# returns sorted numbers (function altered underlying data structure)

Again, notice the order in which each call runs. To understand how merge works, look closely at it. You basically have three pointers and two sorted halves of the initial list that are continually compared. The lowest number during this comparison is set at the index that is being pointed to in the initial list (starting at index 0).

再次注意每个呼叫的运行顺序。 要了解合并的工作原理,请仔细查看它。 基本上,初始列表中有三个指针和两个排序的一半,它们会不断进行比较。 在此比较期间,最低的数字设置为初始列表中指向的索引(从索引0开始)。

Several notes if you are not used to Python. When a function returns nothing, it returns the value None . You can see the frequent return value of None in my diagrams, as there are no explicit return statements in mergeSort.

如果您不习惯使用Python,请注意以下几点。 当一个函数什么都不返回时,它返回值None 。 您可以在图表中看到None的频繁返回值,因为mergeSort中没有显式的return语句。

Also, notice how the list input into the function call is mutated, which is to say that Python did not create a copy of the list when the function was called.

此外,请注意输入到函数调用中的列表的方式是如何突变的,也就是说,调用函数时Python并未创建列表的副本。

河内塔 (Tower of Hanoi)

Here’s a quick story as a side note — I found it to be quite a poetic intro to the Tower of Hanoi:

这是一个简短的故事作为旁注–我发现这是河内塔的诗意介绍:

“Somewhere in a remote region of the world is a monastery of a very devout religious order. The monks have been charged with a sacred task that keeps time for the universe. At the beginning of all things, the monks were given a table that supports three vertical posts. On one of the posts was a stack of 64 concentric, golden disks. The disks are of varying radii and stacked in the shape of a beautiful pyramid. The monks are charged with the task of moving the disks from the first post to the third post. When the monks complete their task, all things will crumble to dust and the universe will end.” — John Zell, Python Programming: An Introduction to Computer Science (2004)

“在世界偏远地区的某个地方,有一个虔诚的宗教秩序的修道院。 僧侣们被控以一项神圣的任务,可以维持宇宙的时间。 一切开始时,僧侣都得到一张桌子,可支撑三个垂直的柱子。 在其中一个柱子上是一叠64个同心的金色磁盘。 这些圆盘具有不同的半径,并以美丽的金字塔形状堆叠。 僧侣负责将磁盘从第一根柱子移到第三根柱子的任务。 和尚完成任务后,万物都会崩溃,宇宙将终结。” — John Zell,《 Python编程:计算机科学概论》(2004年)

def moveTower(n, source, dest, temp):
    if n == 1:
        print("Move disk from", source, "to", dest+".")
    else:
        moveTower(n-1, source, temp, dest)
        moveTower(1, source, dest, temp)
        moveTower(n-1, temp, dest, source)
    
 def hanoi(n):
    moveTower(n, "A", "C", "B")

The moving of the blocks is based upon a mathematical principle.

块的移动基于数学原理

From the Wikipedia article:

维基百科文章

  1. Move m − 1 disks from the source to the temp peg. This leaves the disk m as a top disk on the source peg.

    m − 1个磁盘从源移动临时钉。 这使磁盘m成为源挂钉上的顶部磁盘。

  2. Move the disk m from the source to the dest peg.

    将磁盘m移动到目标钉。

  3. Move the m − 1 disks that we have just placed on the spare from the temp to the dest peg, so they are placed on top of the disk m without violating the rules.

    将我们刚刚放置在备用磁盘上的m -1个磁盘从临时磁盘移至目标挂钉,以便将它们放置在磁盘m的顶部,而不会违反规则。

But how does one make sense of this principle? Well, check this out.

但是,如何理解这一原则呢? 好吧,看看这个。

Notice this: the three rules repeat (black text) except when rule 2 (blue text) runs, because the algorithm does not reach its base case.

请注意:重复执行三个规则(黑色文本),但运行规则2(蓝色文本)时除外,因为该算法未达到其基本情况。

递归一句话 (A word on recursion)

This article is the first step in being able to solve recursive problems. I created this to help readers understand how recursion works, and what the reality of it is. For each problem, notice how I ordered each function invocation and return value. This is the same way that the computer reads the code.

本文是能够解决递归问题的第一步。 我创建此代码是为了帮助读者了解递归的工作原理以及它的现实情况。 对于每个问题,请注意我如何对每个函数调用和返回值进行排序。 这与计算机读取代码的方式相同。

The basic underlying concept of recursion is this:

递归的基本基本概念是:

The function in which the recursive function call was called in must wait for the recursive function call to finish before it continues its process.

在其中调用递归函数调用的函数必须等待递归函数调用完成,然后才能继续执行其过程。

So if the recursive function calls more recursive functions, then it must also wait for those recursive functions to return. Recursion, in a way, just involves functions waiting for the functions they called to return something prior to continuing.

因此,如果递归函数调用更多的递归函数,则它还必须等待这些递归函数返回。 从某种意义上讲,递归仅涉及函数等待它们调用的函数在继续之前返回某些内容。

If you desire to grow in the realm of recursive problem solving, then you must study math. They are one and the same. But going over the math is beyond the scope of this article. This wikipedia article is a nice primer to begin with.

如果您希望在递归问题解决领域中成长,那么您必须学习数学。 他们是一样的。 但是,数学运算超出了本文的范围。 这篇维基百科文章是一个不错的入门书。

That’s that. I must thank, absolutely and completely, Data Structures and Algorithms Using Python and C++ by David M. Reed, as well as John Zelle, since that is where that wonderful quote and the algorithms were mined from.

就是这样。 我必须绝对而完全地感谢David M. Reed和John Zelle撰写的《 使用Python和C ++数据结构和算法》 ,因为那是从中提取了精彩的引文和算法的地方。

And here’s a nice view of space because, well, recursion feels a bit like it.

这是一个不错的空间视图,因为递归有点像它。

翻译自: https://www.freecodecamp.org/news/recursion-visually-explained-bec8cca14d9b/

sql 一张表递归

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值