#Created By: Chen Da
"""
阶乘函数就是典型的递归:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
递归的特点:
递归必须包含一个基本的出口(base case),否则就会无限递归,最终导致栈溢出。比如这里就是n==0时返回1.
递归必须包含一个可以分解的问题(recursive case)。想求得fact(n),就要用n*fact(n-1)。
递归必须要向着递归出口靠近(toward the base case)。这里每次递归调用都会n-1,向着递归出口n==0靠近。
"""
'''
#倒序打印
def print_new(n):
if n > 0:
print(n)
print_new(n - 1) #尾递归
print_new(10)
'''
#导入内置双端队列
from collections import deque
#计算机中是用栈来实现递归
#定义一个栈
class Stack(object):
def __init__(self):
self._deque = deque()
def push(self,value):
return self._deque.append(value)
def pop(self):
return self._deque.pop()
def is_empty(self):
return len(self._deque) == 0
def print_stack(n):
s = Stack()
while n > 0: #n不为0时持续入栈
s.push(n)
n -= 1
while not s.is_empty(): #s不为空时,后进先出
print(s.pop())
print_stack(10)
11_数据结构与算法_递归_Python实现
猜你喜欢
转载自blog.csdn.net/PyDarren/article/details/83477951
今日推荐
周排行