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 hanoi_loop(n):
"""
The loop version of hanoi_recur.
"""
if n==1:
return 1,1
stack = [Stack(n=n,stage=0,)]
cache={1:1}
while stack:
crt=stack.pop()
if crt.n in cache:
psb_v = 2*cache[crt.n]+2**crt.i-1
crt.prt.psb.append((crt.i,psb_v))
continue
if crt.stage==0:
crt.stage, crt.pgs, crt.psb= 1, 0, []
stack.append(crt)
continue
if crt.stage==1:
if crt.pgs != crt.n - 1:
crt.pgs += 1
stack.append(crt)
chd = Stack(n=crt.pgs, stage=0, i=crt.n-crt.pgs, prt=crt)
stack.append(chd)
else:
crt.stage=2
stack.append(crt)
continue
if crt.stage==2 and hasattr(crt,'prt'):
#hasattr - the last stack doesn't have attribute 'prt',
#so it has to be excluded here.
_, min_v = min(crt.psb,key=lambda x:x[1])
psb_v = 2*min_v + 2**crt.i - 1
crt.prt.psb.append((crt.i,psb_v))
cache[crt.n] = min_v
continue
return min(crt.psb,key=lambda x:x[1]) if __name__=='__main__':
is_equal(range(1,300),hanoi_loop,hanoi_recur)
print('passed test!')

最新文章

  1. 简单的验证码识别(opecv)
  2. TF400324: Team Foundation services are not available from server…
  3. VS自动生成的packages.config配置文件有什么用?
  4. 分层开发之MySchool
  5. ***PHP类型转换实例:$this->input->get()返回的结果是字符串类型(数字字符串转数字)
  6. Sql2008 php
  7. Huffman树的编码译码
  8. TraceGL监控Node.js应用或者浏览器JavaScript代码
  9. UESTC_Ferris Wheel String 2015 UESTC Training for Search Algorithm & String<Problem L>
  10. 闲扯 Javascript 04 滚动条
  11. NSIS:安装、卸载时检查程序是否正在运行
  12. IOC容器在框架中的应用
  13. java版微信公众平台自定义菜单创建代码实现
  14. 使用 IDEA 创建 Maven Web 项目 (四)- 让 WEB 应用跑起来
  15. Thinkpad T450 Linux Mint(Ubuntu) 安装Nvidia显卡驱动
  16. 没有robots.txt文件是否会影响收录呢
  17. MySQL学习(四)Join 等开发常用的操作 --- 2019年2月
  18. 如何發佈一個完整Node.js Module
  19. 转载:img是什么元素?置换元素?
  20. SQLServer修改表数据

热门文章

  1. 用js来实现那些数据结构07(链表01-链表的实现)
  2. PostgreSQL的insert注入
  3. cogs 619. [金陵中学2007] 传话
  4. [SDOI2008]Sue的小球
  5. [USACO17JAN]Promotion Counting晋升者计数
  6. ●BZOJ 3963 [WF2011]MachineWorks
  7. 例10-2 uva12169(扩展欧几里得)
  8. hdu3567 八数码(搜索)--预处理
  9. [bzoj4161]Shlw loves matrix I
  10. 用js来实现那些数据结构11(字典)