Chinaunix

标题: 排列算法例子 [打印本页]

作者: tubocurarine    时间: 2009-10-13 13:31
标题: 排列算法例子

               
               
                class Permutation:
    def __init__(self, justalist):
        self._data = justalist[:]
        self._sofar = []
    def __iter__(self):
        return self.next()
    def next(self):
        for elem in self._data:
            if elem not in self._sofar:
                self._sofar.append(elem)
                if len(self._sofar) == len(self._data):
                    yield self._sofar[:]
                else:
                    for v in self.next():
                        yield v
                self._sofar.pop()
a=[1,2,3,4]
for i in Permutation(a):
    print i
    刚刚从http://ttsiodras.googlepages.com/index.html看到的,很不错,用到了yield和generator的东西,值得借鉴。


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/46672/showart_2069243.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2