随笔分类 -  Python

摘要:def xwhile_stacks(n): stacks = [(0,n,None,None,)] while stacks: stg,n,possible,choice=stacks.pop() if stg==0: if n==1: res = 1,0 else: stacks.append((1,n,[],n-1)) stacks.append((0,1,None,None)) else: ... 阅读全文
posted @ 2014-03-18 13:35 LisPythoniC 阅读(221) 评论(0) 推荐(0)
摘要:记住经典的斐波拉契递归和阶乘递归转换为while规律.它为实现更复杂转换提供了启发性思路.# 斐波拉契--树形递归def fab(n): if n<3: return n return fab(n-1)+fab(n-2)def wfab(n): stacks=[(0,... 阅读全文
posted @ 2014-03-17 23:59 LisPythoniC 阅读(517) 评论(0) 推荐(0)
摘要:前段时间用类似于散弹式编程的方式,各种猜测-运行验证-修正结果,最终成功转换了一个看起来比较有难度的递归函数.但总觉得很蛋疼,原因如下:1.虽然正确,但是逻辑搞得比较复杂.现在去看,一头雾水,不知道当时是怎么想的,也没有任何欲望去理解.2.没有充分利用本地变量,而是保守地把当前栈的数据一股脑绑定到Stack对象上.3.我需要用一个Class来保存栈吗?是不是太重了?为什么不考虑用一个简单的tuple来实现呢?def recur(n): if n==1: return 1,0 return min([(2*recur(n-i)[0]+2**i-1,i) for i in... 阅读全文
posted @ 2014-03-17 23:34 LisPythoniC 阅读(308) 评论(0) 推荐(0)
摘要:>>> def f(): return 2>>> -f()-2初一看,-f()比较陌生的样子,细想,这是合理的 阅读全文
posted @ 2014-03-14 21:33 LisPythoniC 阅读(399) 评论(0) 推荐(0)
摘要:我发现当参数并不太多时,从性能的角度来看,没必要用一个class来保存参数(虽然看起来更加生动形象),直接用最简单的元组就可以了.from hanoi import *# example trees for test...trees=[]trees.append(None)trees.append([1,None,None])trees.append([1,None,[2,None,None]])trees.append([1,[3,[4,None,None],None],[600,None,None]])trees.append([1,[3,[4,None,None],[6,None,Non 阅读全文
posted @ 2014-03-14 17:05 LisPythoniC 阅读(252) 评论(0) 推荐(0)
摘要:>>> qs=Question.objects.extra(select={'anum': 'SELECT COUNT(*) FROM questions_answer WHERE questions_answer.question_id = questions_question.id'},).extra(order_by=['-anum'])>>> [q.anum for q in qs][3, 3, 3, 3, 2, 2, 1, 1, 1, 0, 0, 0, 0]>>> qs2=Quest 阅读全文
posted @ 2014-03-05 00:48 LisPythoniC 阅读(621) 评论(0) 推荐(0)
摘要: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 阅读全文
posted @ 2014-02-27 23:46 LisPythoniC 阅读(273) 评论(0) 推荐(0)
摘要:def hanoi_recur(n,reverse=True): if n==1: return 1,1 possible=[] iter_range=range(n-1,0,-1) if reverse else range(1,n) for i in iter_range: _, min_v = hanoi_recur(n-i,reverse) possible.append((i,2*min_v+2**i-1)) return min(possible,key=lambda x:x[1])如上所示,hanoi_rec... 阅读全文
posted @ 2014-02-27 23:39 LisPythoniC 阅读(257) 评论(0) 推荐(0)
摘要:class Stack(object): def __init__(self,**kwargs): self.__dict__.update(kwargs) def __str__(self): return '|'.join( ['%s:%s'%(k,getattr(self,k)) for k in sorted(self.__dict__)]) __repr__ = __str__def fab(n): if n==1 or n==2: return 1 return f... 阅读全文
posted @ 2014-02-26 17:41 LisPythoniC 阅读(297) 评论(0) 推荐(0)
摘要:摘自Handling Arbitrary StructuresOn the other hand, recursion—or equivalent explicit stack-based algorithms we’ll meetshortly—can be required to traverse arbitrarily shaped structures. As a simple exampleof recursion’s role in this context, consider the task of computing the sum of all thenumbers in a 阅读全文
posted @ 2014-02-23 15:25 LisPythoniC 阅读(450) 评论(0) 推荐(0)
摘要:def moves_three(n, a=0, b=1, c=2): '''give a int -> return a list ''' if n==1: return ((a,c),) return moves_three(n-1,a,c,b)+\ ((a,c),)+\ moves_three(n-1,b,a,c)def moves(n, a=0, b=1, c=2): stack = [(True, n, a, b, c)] while stack: tag, n, a, b, c = st... 阅读全文
posted @ 2014-02-23 13:59 LisPythoniC 阅读(234) 评论(0) 推荐(0)
摘要:我发现从人的角度来看,以最少的代码解决最复杂的问题的思维方式应该是递归,无论是以前接触到的经典的斐波拉契函数还是最近研究的Hanoi变体-4柱最优步骤生成函数(注意,不仅仅是得出最小的步骤总数).非线性递归---尾递归---迭代遗憾的是,从右到左,对计算机是越来越不友好. 而从非线性递归转化为尾递归相对来说要容易一些, 如果有一个装饰器,它能够使所有尾递归函数自动变为等价的迭代函数,那么就相当于极大扩展了递归在Python的应用空间.还真就有这种装饰器!今天无意发现的.class TailRecursive(object): """ tail_recursive 阅读全文
posted @ 2014-02-22 23:29 LisPythoniC 阅读(851) 评论(0) 推荐(0)
摘要:import re,osdef org(path=os.getcwd(),fs=None,preview=True): fs = fs or [] for root,dirs,files in os.walk(path): for f in files: if f[-4:]=='html': fp=os.path.join(root,f) s=open(fp,encoding='u8').read() for func in fs: ... 阅读全文
posted @ 2014-02-20 16:09 LisPythoniC 阅读(263) 评论(0) 推荐(0)
摘要:今天,我总算搞清楚“回车”(carriage return)和“换行”(line feed)这两个概念的来历和区别了。在计算机还没有出现之前,有一种叫做电传打字机(Teletype Model 33)的玩意,每秒钟可以打10个字符。但是它有一个问题,就是打完一行换行的时候,要用去0.2秒,正好可以打两个字符。要是在这0.2秒里面,又有新的字符传过来,那么这个字符将丢失。于是,研制人员想了个办法解决这个问题,就是在每行后面加两个表示结束的字符。一个叫做“回车”,告诉打字机把打印头定位在左边界;另一个叫做“换行”,告诉打字机把纸向下移一行。这就是“换行”和“回车”的来历,从它们的英语名字上也可以看 阅读全文
posted @ 2014-01-31 11:33 LisPythoniC 阅读(357) 评论(0) 推荐(0)
摘要:>>> import datetime>>> class c(): @property def noww(self): return datetime.datetime.now() >>> c.noww>>> x=c()>>> x.nowwdatetime.datetime(2014, 1, 27, 13, 17, 14, 725610)>>> x.nowwdatetime.datetime(2014, 1, 27, 13, 17, 27, 8740)>>> x.now 阅读全文
posted @ 2014-01-27 13:19 LisPythoniC 阅读(244) 评论(0) 推荐(0)
摘要:>>> def f(): a=1 return [i+a for i in range(3)]>>> f()[1, 2, 3]>>> def f(): a=1 return [i+eval('a') for i in range(3)]>>> f()Traceback (most recent call last): File "", line 1, in f() File "", line 3, in f return [i+eval('a') fo 阅读全文
posted @ 2014-01-26 17:57 LisPythoniC 阅读(234) 评论(0) 推荐(0)
摘要:>>> dict({1:2},2=3)SyntaxError: keyword can't be an expression>>> dict({1:2},**{2:3})Traceback (most recent call last): File "", line 1, in dict({1:2},**{2:3})TypeError: keyword arguments must be strings>>> dict({1:2},**{'2':3}){1: 2, '2': 3}& 阅读全文
posted @ 2014-01-07 21:42 LisPythoniC 阅读(783) 评论(0) 推荐(0)
摘要:最近读django源码,发现必须了解元类才能理解一些很神奇的行为.发现元类实际上是控制class的创建过程.比如类B继承某个看似平淡无奇的类A之后,你在类B中定义的属性或方法可能会遭到彻底改变.假设我们想实现这么一种需求:创建一个类Child,在这个类中定义的种种字符串属性,都可以当做对应的函数那样调用.例如:class Child(): f1='print'随后,Child.f1就完全和内建函数print等价了.Child.f1('abc')能够打印出abc这个字符串.这样来说,元类的用途看起来可以是:一些高手设计了一个在幕后做了很多工作的元类,另一些开发人员 阅读全文
posted @ 2014-01-07 11:25 LisPythoniC 阅读(342) 评论(0) 推荐(0)
摘要:#\Python33\Lib\site-packages\django\contrib\auth\models.pyclass UserManager(BaseUserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given username, email and password. ... 阅读全文
posted @ 2014-01-05 16:08 LisPythoniC 阅读(202) 评论(0) 推荐(0)
摘要:Basic configuration and use---------------------------Once installed, you can add django-registration to any Django-basedproject you're developing. The default setup will enable userregistration with the following workflow:1. A user signs up for an account by supplying a username, email address 阅读全文
posted @ 2014-01-03 15:16 LisPythoniC 阅读(387) 评论(0) 推荐(0)