手机网站开发标准,贵州企业网站,购物网站用html怎么做,衡水网站建设培训学校from python cookbook 19.15 任务 需要对一个序列的排列#xff08;permutation#xff09;、组合#xff08;combination#xff09;或选择#xff08;selection#xff09;进行迭代操作。即使初始的序列长度并不长#xff0c;组合计算的规则却显示生成的序列可… from python cookbook 19.15 任务 需要对一个序列的排列permutation、组合combination或选择selection进行迭代操作。即使初始的序列长度并不长组合计算的规则却显示生成的序列可能非常庞大比如一个长度为13的序列有超过60亿种可能的排列。所以你肯定不希望在开始迭代前计算并生成序列中的所有项 解决方案 生成器允许你在迭代的时候一次一个的计算需要的对象。如果有很多这种对象而且你也必须逐个的检查他们那么程序无可避免的会用很长时间才能完成循环。但至少你不用浪费很多内存来保存所有项 def _combinators(_handle, items, n): 抽取下列组合的通用结构if n 0:yield [ ]for i, item in enumerate(items):this_one [item]for cc in _combinators(_handle, _handle(items, i), n-1):yield this_one ccdef combinations(items, n): 取得n个不同的项 顺序是有意义的def skipIthItem(items, i):return items[:i] items[i 1:]return _combinators(skipIthItem, items, n)def uniqueCombinations(items, n):取得n个不同的项顺序无关def afterIthItem(items, i):return items[i1:]return _combinators(afterIthItem, items, n)def selections(items, n):取得n项不一定要不同顺序是有意义的def keepAllItems(items, i):return itemsreturn _combinators(keepAllItems, items, n)def permutations(items): 取得所有项 顺序是有意义的return combinations(items, len(items))if __name__ __main__:print Permutations of barprint map(.join, permutations(bar))
#输出 [bar, bra, abr, arb, rba, rab]print Combinations of 2 letters from barprint map(.join, combinations(bar, 2))
# 输出 [ba, br, ab, ar, rb, ra]print Unique Combinations of 2 letters from barprint map(.join, uniqueCombinations(bar, 2))
# 输出: [ba, br, ar]print Selections of 2 letters from barprint [.join, selections(bar, 2)]
# 输出 [bb, ba, br, ab, aa, ar, rb, ra, rr] 转载于:https://www.cnblogs.com/siriuswang/p/4638816.html