python排列組合之itertools模組

2022-09-15 15:33:21 字數 1606 閱讀 2974

幾個有用的python函式 (笛卡爾積, 排列, 組合)

9.7. itertools — functions creating iterators for efficient looping

1

#有序排列permutations a。2#

不放回抽球兩次,r引數預設為len('abc')

3 >>> for i in itertools.permutations('

abc',2):

4 ... print

(i)5

...6 ('

a', 'b'

)7 ('

a', 'c'

)8 ('

b', 'a'

)9 ('

b', 'c'

)10 ('

c', 'a'

)11 ('

c', 'b'

)12#無序組合combinations c。13#

不放回抽球兩次,r必選

14 >>> for i in itertools.combinations('

abc',2):

15 ... print

(i)16

...17 ('

a', 'b'

)18 ('

a', 'c'

)19 ('

b', 'c'

)20212223#

笛卡爾積24#

放回抽球,預設repeat=125#

product(a, b) returns the same as: ((x,y) for x in a for y in b).26#

repeat=2相當於for i in itertools.product('abc','abc')

27 >>> for i in itertools.product('

abc',repeat=2

):28 ... print

(i)29

...30 ('

a', 'a'

)31 ('

a', 'b'

)32 ('

a', 'c'

)33 ('

b', 'a'

)34 ('

b', 'b'

)35 ('

b', 'c'

)36 ('

c', 'a'

)37 ('

c', 'b'

)38 ('

c', 'c'

)39#放回抽球,r必選,相當於product再去掉非自定義字典序'cba'順序的

40 >>> for i in itertools.combinations_with_replacement('

cba', 2):

41 ... print

(i)42

...43 ('

c', 'c'

)44 ('

c', 'b'

)45 ('

c', 'a'

)46 ('

b', 'b'

)47 ('

b', 'a'

)48 ('

a', '

a')

python 排列組合

from scipy.special import comb,perm 計算排列數 a perm 3,2 計算組合數 c comb 45,2 print int a int c 6 990方法 說明種類 permutations 排列不放回抽樣排列 combinations 組合,沒有重複 不放回抽...

python實現排列組合

排列組合是組合學最基本的概念。所謂排列,就是指從給定個數的元素中取出指定個數的元素進行排序。組合則是指從給定個數的元素中僅僅取出指定個數的元素,不考慮排序。itertools參考文件 import itertools itertools.combinations iterable,r 引數說明 it...

Python排列組合模板

筆試題第乙個往往涉及到排列組合的問題,本文將給出乙個python語言的排列和組合的 模板,像記住快排一樣能夠在各種筆試面試演算法題中熟練默寫。46.全排列 77.組合 78.子集 本文依託這兩個題,並給出更為通用的排列組合模板,分析時間複雜度和空間複雜度,力圖完全掌握這兩個演算法。回溯法全排列 從s...