python 生成排列、组合以及选择
生活随笔
收集整理的這篇文章主要介紹了
python 生成排列、组合以及选择
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
from <python cookbook> 19.15
任務(wù)
需要對一個序列的排列(permutation)、組合(combination)或選擇(selection)進(jìn)行迭代操作。即使初始的序列長度并不長,組合計算的規(guī)則卻顯示生成的序列可能非常龐大,比如一個長度為13的序列有超過60億種可能的排列。所以,你肯定不希望在開始迭代前計算并生成序列中的所有項
解決方案
生成器允許你在迭代的時候一次一個的計算需要的對象。如果有很多這種對象,而且你也必須逐個的檢查他們,那么程序無可避免的會用很長時間才能完成循環(huán)。但至少你不用浪費很多內(nèi)存來保存所有項:
def _combinators(_handle, items, n):''' 抽取下列組合的通用結(jié)構(gòu)'''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個不同的項,順序無關(guān)'''def afterIthItem(items, i):return items[i+1:]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 'bar'"print map(''.join, permutations('bar')) #輸出: ['bar', 'bra', 'abr', 'arb', 'rba', 'rab']print "Combinations of 2 letters from 'bar'"print map(''.join, combinations('bar', 2)) # 輸出: ['ba', 'br', 'ab', 'ar', 'rb', 'ra']print "Unique Combinations of 2 letters from 'bar'"print map(''.join, uniqueCombinations('bar', 2)) # 輸出: ['ba', 'br', 'ar']print "Selections of 2 letters from 'bar'"print [''.join, selections('bar', 2)] # 輸出: ['bb', 'ba', 'br', 'ab', 'aa', 'ar', 'rb', 'ra', 'rr']?
轉(zhuǎn)載于:https://www.cnblogs.com/siriuswang/p/4638816.html
總結(jié)
以上是生活随笔為你收集整理的python 生成排列、组合以及选择的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 读《一个程序猿的生命周期》有感
- 下一篇: Python easy_install