import sections


In [2]:
from functools import wraps
import logging as Log
from inspect import Signature, Parameter

Log.basicConfig(format='%(asctime)s %(message)s', level=Log.INFO)

__author__ = 'chois'

In [29]:
"""
Node 为迭代对象

"""

class Node:
    def __init__(self, value):
        self._value = value
        self._children = []

    def __repr__(self):
        return 'Node({!r})'.format(self._value)

    def add_child(self, node):
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

    def depth_first(self):
        return DepthFirstIterator(self)


class DepthFirstIterator(object):
    '''
    Depth-first traversal
    '''

    def __init__(self, start_node):
        self._node = start_node
        self._children_iter = None
        self._child_iter = None

    def __iter__(self):
        Log.info(f'iter:{self._children_iter}')
        return self

    def __next__(self):
#         Log.info(f'next---:{self._children_iter}')
        # Return myself if just started; create an iterator for children
        if self._children_iter is None:
            self._children_iter = iter(self._node)
            return self._node
        # If processing a child, return its next item
        elif self._child_iter is not None:
            try:
                nextchild = next(self._child_iter)
                return nextchild
            except StopIteration:
                self._child_iter = None
                return next(self)
        # Advance to the next child and start its iteration
        else:
            self._child_iter = next(self._children_iter).depth_first()
            return next(self)

In [30]:
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
child2.add_child(Node(6))
child3.add_child(Node(7))
child3.add_child(Node(8))

In [31]:
for ch in root.depth_first():
    Log.info(ch)


2017-09-10 10:25:38,255 iter:None
2017-09-10 10:25:38,259 Node(0)
2017-09-10 10:25:38,267 Node(1)
2017-09-10 10:25:38,271 Node(3)
2017-09-10 10:25:38,275 Node(4)
2017-09-10 10:25:38,283 Node(2)
2017-09-10 10:25:38,287 Node(5)
2017-09-10 10:25:38,295 Node(6)

In [109]:
class Fib(object):
    def __init__(self, n):
        self.a = 0
        self.b = 1
        self.end = n
    
    def __iter__(self):
#         con = 0 
#         con += 1
#         Log.info('__iter__ at {!r}'.format(con))
        return self
    
    def __next__(self):
#         con = 0 
#         con += 1
#         Log.info('__next__ at {!r}'.format(con))
        self.a, self.b = self.b, self.a + self.b
        if self.a > self.end:
            raise StopIteration();
        else:
            return self.a
        
    def __repr__(self):
        return 'fib {!r}'.format(self.a)

fb = Fib(5)
# iter(fb)
# for _ in fb:
#     iter(fb)
# try:
for f in fb:
    Log.info(f)
# except StopIteration:
#     Log.info('end!')


2017-09-03 12:00:57,327 __iter__ at 1
2017-09-03 12:00:57,337 __next__ at 1
2017-09-03 12:00:57,345 1
2017-09-03 12:00:57,347 __next__ at 1
2017-09-03 12:00:57,359 1
2017-09-03 12:00:57,363 __next__ at 1
2017-09-03 12:00:57,371 2
2017-09-03 12:00:57,375 __next__ at 1
2017-09-03 12:00:57,383 3
2017-09-03 12:00:57,387 __next__ at 1
2017-09-03 12:00:57,403 5
2017-09-03 12:00:57,407 __next__ at 1

In [102]:
class CP(object):
    def __init__(self):
        self.x = 0
        pass

class C(CP):
        @property
        def x(self):
            "I am the 'x' property."
            return self._x
        @x.setter
        def x(self, value):
            self._x = value
        @x.deleter
        def x(self):
            del self._x
c= C()
# c.x = 2
c.x
del c.x

In [8]:
def f():
    try:
        yield 1
        try:
            yield 2
            1 / 0
            yield 3  # never get here
        except ZeroDivisionError:
            yield 4
            yield 5
            raise  # reactivate last activate except t0 yield 8
        except:
            yield 6
        yield 7  # the "raise" above stops this
    except:
        yield 8
    yield 9
#     ------------------------------------------
    try:
        x = 12
    finally:
        yield 10
    yield 11
Log.info(list(f()))


2017-09-10 18:12:34,011 [1, 2, 4, 5, 8, 9, 10, 11]

In [3]:
# A binary tree class.
class Tree:

    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right

    def __repr__(self, level=0, indent="    "):
        s = level*indent + f'{self.label}'
        if self.left:
            s = s + "\n" + self.left.__repr__(level+1, indent)
        if self.right:
            s = s + "\n" + self.right.__repr__(level+1, indent)
        return s

    def __iter__(self):
        return inorder(self)
    
# A recursive generator that generates Tree labels in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x


# Create a Tree from a list.
def tree(list):
    n = len(list)
    if n == 0:
        return []
    i = int(n / 2)
    return Tree(list[i], tree(list[:i]), tree(list[i+1:]))


# Show it off: create a tree
t = tree("1234567")
list(t)


Out[3]:
['1', '2', '3', '4', '5', '6', '7']

Binary Tree


In [33]:
class List(object):
    def __init__(self, center, left: list=None, right: list=None):
        self.center = center
        self.left = left
        self.right = right
    
    def __iter__(self):
        """iterator """
        return right_out(self)

def right_out(lst):
    """
    generator 
    """
#     二叉树算法
    if lst:
        
        for x in right_out(lst.right):  # 右子树遍历,直至[]返回
            yield x  # 不会返回x
        
        # 记录lst Node节点
        yield lst.center
        
        for x in right_out(lst.left):  # 左子树遍历,直至[]返回
            yield x  # 
            
            

def iter_tree(lst):
    """
    生成可以迭代对象的迭代器
    """
    n= len(lst)
    if n == 0:
        return []
    
    i = int(n/2)
#     Log.info('{}'.format(lst[i]))
#     List实例初始化
    return List(lst[i], iter_tree(lst[0:i]), iter_tree(lst[i+1:]))  # 返回迭代对象

l_t = iter_tree([1,2,3,4,5,6,7,8])
for x in l_t:
    Log.info(x)


2017-09-10 10:53:38,443 8
2017-09-10 10:53:38,451 7
2017-09-10 10:53:38,459 6
2017-09-10 10:53:38,471 5
2017-09-10 10:53:38,479 4
2017-09-10 10:53:38,483 3
2017-09-10 10:53:38,491 2
2017-09-10 10:53:38,495 1