码迷,mamicode.com
首页 > 编程语言 > 详细

递归(python)

时间:2019-07-10 23:09:19      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:else   media   noi   inter   递归   code   object   init   lis   

# -*- coding: utf-8 -*-

def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n - 1)


def print_num(n):
    for i in range(1, n + 1):    #
        print(i)


def print_num_recursive(n):
    if n > 0:
        print_num_recursive(n - 1)
        print(n)


def print_num_recursive_revserve(n):
    if n > 0:
        print(n)
        print_num_recursive_revserve(n - 1)


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_num_use_stack(n):
    s = Stack()
    while n > 0:    # 不断将参数入栈
        s.push(n)
        n -= 1

    while not s.is_empty():    # 参数弹出
        print(s.pop())


def hanoi_move(n, source, dest, intermediate):
    if n >= 1:  # 递归出口,只剩一个盘子
        hanoi_move(n - 1, source, intermediate, dest)
        print("Move %s -> %s" % (source, dest))
        hanoi_move(n - 1, intermediate, dest, source)


def flatten(rec_list):
    for i in rec_list:
        if isinstance(i, list):
            for i in flatten(i):
                yield i
        else:
            yield i


def test_flatten():
    assert list(flatten([[[1], 2, 3], [1, 2, 3]])) == [1, 2, 3, 1, 2, 3]

 

递归(python)

标签:else   media   noi   inter   递归   code   object   init   lis   

原文地址:https://www.cnblogs.com/muzinan110/p/11166967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!