一个貌似比较吊的递归转换为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 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!')
一个貌似比较吊的递归转换为loop--总算成功了.的更多相关文章
- 一个貌似比较吊的递归转换为loop--总算成功了.--第二弹
前段时间用类似于散弹式编程的方式,各种猜测-运行验证-修正结果,最终成功转换了一个看起来比较有难度的递归函数.但总觉得很蛋疼,原因如下: 1.虽然正确,但是逻辑搞得比较复杂.现在去看,一头雾水,不知道 ...
- 将树形递归转换为loop
class Stack(object): def __init__(self,**kwargs): self.__dict__.update(kwargs) def __str__(self): re ...
- 记住经典的斐波拉契递归和阶乘递归转换为while规律
记住经典的斐波拉契递归和阶乘递归转换为while规律.它为实现更复杂转换提供了启发性思路. # 斐波拉契--树形递归 def fab(n): if n<3: return n return fa ...
- 一个超复杂的间接递归——C语言初学者代码中的常见错误与瑕疵(6)
问题: 问题出处见 C语言初学者代码中的常见错误与瑕疵(5) . 在该文的最后,曾提到完成的代码还有进一步改进的余地.本文完成了这个改进.所以本文讨论的并不是初学者代码中的常见错误与瑕疵,而是对我自己 ...
- 求一个集合S中m个元素的所有排列以及一个数组A的全排列—递归实现版完整代码
说明,本文全文代码均用dart语言实现. 求一个集合S中m个元素的所有排列情况,并打印,非常适合用递归的思路实现.本文给出了两种实现方法,一种是给定的填充排列数组长度是固定的,一种是可变长度的.两种方 ...
- 驳 GarbageMan 的《一个超复杂的简介递归》——对延迟计算的实验和思考
这是一篇因骂战而起的博文,GarbageMan 在该文章回复中不仅对我进行了侮辱,还涉及了我的母校,特写此文用理性的分析和实验予以回击. 在此也劝告 GarbageMan,没什么本事就别在那叫嚣了,还 ...
- 不规则递归转换为while,留底
我发现当参数并不太多时,从性能的角度来看,没必要用一个class来保存参数(虽然看起来更加生动形象),直接用最简单的元组就可以了. from hanoi import * # example tree ...
- 在主函数中提示用户输入用户名和密码。另写一方法来判断用户输入是否正确。该方法分别返回一个bool类型的登录结果和和一个string类型的登录信息。如登录成功,返回true及“登录成功”,若登录失败则返回false及“用户名错误”或“密码错误”(使用out参数)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- shell脚本安装python、pip--这种写法是错误的---每一个命令执行完都要判断是否执行成功,否则无法进行下一步
shell脚本安装python.pip--不需要选择安装项目--不管用总报错,必须带上判断符号,while没有这种用法,写在这里为了以后少走弯路,所以不要用下面的执行了 首先把pip-.tgz 安装包 ...
随机推荐
- 0417 jsBom操作+Dom再次整理
BOM 1.Windows对象 window.open("打开的地址","打开的位置")window.opener:打开此页面的上一个页面对象window.cl ...
- XMLHTTPRequestObject获取服务器数据
http://www.educity.cn/develop/526316.html 在Web客户端使用xmlhttp对象,可以十分方便的和服务器交换数据,我们可以获取和发送任何类型的数据,甚至二进制数 ...
- Hibernate--对象关系
在hibernate中,关联关系映射分为单向关联和双向关联.共有七种关系 ·@Many To One ·@One To Many(单向) ·@One To Many(多向) ·@One To One( ...
- keil应用小贴士:Use MicroLIB是干什么的
在keil 建立ARM的工程时,其中有一项是选 use MicroLIB 查了查,得到了以下信息: microlib 是缺省 C 库的备选库. 它旨在与需要装入到极少量内存中的深层嵌入式应用程序配合使 ...
- 【HDU 1576】 A/B
Problem Description 要求(A/B)%9973,但由于A很大,我们只给出n(n=A%9973)(我们给定的A必能被B整除,且gcd(B,9973) = 1). Input 数据的 ...
- 【LSGDOJ1834 Tree】树链剖分
题目描述 给定一个N个结点的无向树,树中的结点按照1...N编号,树中的边按照1...N − 1编号,每条边都赋予一个权值.你需要编写程序支持以下三种操作: 1. CHANGE i v:将i号边 ...
- ●BZOJ 2329 [HNOI2011]括号修复.cpp
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2329 题解: Splay 类似 BZOJ 2329 [HNOI2011]括号修复 只是多了一 ...
- ●BZOJ 2393 Cirno的完美算数教室
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=2393 题解: 容斥原理,暴力搜索,剪枝...和 [Scoi2010 幸运数字] 一样的(只是 ...
- hdu 5119(2014北京)
题意: 随机选择一个数,如果后面有比他小的就进行交换,直到没有为止(算一轮).求多少轮后为递增序列 思路: 倒着找,如果有比经过的最小数大的,ans+1 #include <iostream&g ...
- 2017ACM/ICPC广西邀请赛-重现赛 1007.Duizi and Shunzi
Problem Description Nike likes playing cards and makes a problem of it. Now give you n integers, ai( ...