Liuw's Thinkpad

想要赢就先学会输,想要成功就先学会失败

Archive for the ‘dynamic function’ tag

再放一个Python写的Combination函数

without comments

前几天写的,动态生成函数。

非Stackless的Python做递归时实在有够慢,而且吃内存太多了。

不幸的是,我刚写完这个函数,就发现用Stackless Python跑原来的程序快得很。浪费时间了。

所以,最后还是用Stackless Python来跑了,不过这个东西还是放上来吧。跑起来比原来的CPython还是快不少的,因为用的都是循环。但是有一个限制,就是循环的最高嵌套数目是20。

# -*- coding: utf-8 -*-
#!/usr/bin/python

# non-recursive combination
# liuw

def MakeCombinationFunction(name, n, k):
    '''
This function returns a function object which will generate indexs
for combination.

name function name
n    total element count
k    take k elements from n, maximum is 20
    '''
    if k > n:
        k = n
    constructs = [('%sfor i%d in xrange(i%d+1, %d):\n'%(' '*(i+1)*4, i+1, i, n),
                   'i%d'%(i+1,))
                  for i in range(k)]
    f, a = map(None, *constructs)
    level = len(constructs)
    f = ' '.join(f)
    source = '    i0 = -1\n' + f + '%syield [%s]' % (' '*4*(level+1), ','.join(a))
    source = 'def %s():\n' % name + source
    scope = {}
    exec source in scope
    return scope[name]

Written by liuw

August 24th, 2009 at 9:31 am