让我们写一些代码:
def greater_less(v, l):
# First, are we in the base case?
if not l:
return [], []
# Second, do the recursive step
smaller, greater = greater_less(v, l[1:])
# Now, we also have l[0] to insert into these lists.
if l[0] < v:
smaller.insert(0, l[0])
elif l[0] > v:
greater.insert(0, l[0])
else:
pass
# Finally, return these lists
return smaller, greater
请注意,我们存储递归调用返回的列表,添加到正确的列表,然后返回。
让我们看一下这段代码的运行。为了减少重复,我将标记函数 A 到 D 中的 4 段代码。所以 A 将是基本情况检查 (if not l...) 而 C 将是 if l[0] < v ... else: pass 代码。
main() calls greater_less(2, [1,2,3])
A: We are not in the base case because l has 3 elements.
B: Recursive call of greater_less(2, [2, 3])
A: We are not in the base case because l has 2 elements.
B: Recursive call of greater_less(2, [3])
A: We are not in the base case because l has 1 element.
B: Recursive call of greater_less(2, [])
A: We __are__ in the base case because l has 0 elements.
Therefore, we won't reach B, C, or D of this call.
We return [], [].
B: Recursive call returns. We have smaller = [], greater = []
C: l[0] is 3 which is greater than 2.
Therefore, we prepend onto greater.
D: Return smaller = [], greater = [3]
B: Caller returns. We have smaller = [], greater = [3]
C: l[0] is 2, which is equal to 2.
So we don't prepend this number to either list.
D: return smaller = [], greater = [3]
B: Caller returns. We have smaller = [], greater = [3]
C: l[0] is 1, which is less than 2.
So prepend to the smaller list.
D: Return smaller = [1], greater = [3]
main's call to greater_less() now returns with ([1], [3])