zoukankan      html  css  js  c++  java
  • 一个貌似比较吊的递归转换为loop--总算成功了.

    class Stack(object):
        """
        A class to hold arguements and state data.
        """
        def __init__(self,**kwargs):
            self.__dict__.update(kwargs)
    
        def __repr__(self):
            extra = "|i:%s"%self.i if hasattr(self,'i') else ''
            return "n:%s|stage:%s%s"%(self.n,self.stage,extra)
        
    def memory(function):
        """
        A decorator to help a no-side-effect function avoid
        repeative calculation.
        """
        cache = {}
        def memofunc(*nkw,**kw):
            key=str(nkw)+str(kw)
            if key not in cache:            
                cache[key] = function(*nkw,**kw)
            return cache[key]
        return memofunc
    
    def is_equal(rg,*funclist):
        """
        to test whether or not a list of one-arguement functions
        have the same output if given same arguement.
        """
        for n in rg:
            rst=[]
            for func in funclist:
                rst.append(func(n))
                assert len(set(rst))==1
    
    @memory
    def hanoi_recur(n):
        """
        n -> (i,v)
        a recursive function to get the smallest number i
        and correspondent value.
        """
        if n==1:
            return 1,1
        psb=[]
        for i in range(n-1,0,-1):
            _, min_v = hanoi_recur(n-i)
            psb_v = 2*min_v+2**i-1
            psb.append((i,psb_v))
        return min(psb,key=lambda x:x[1])
    
    @memory
    def