python內建排列組合函式

2021-10-23 17:07:25 字數 1873 閱讀 1904

python內建函式-排列組合函式

product 笛卡爾積  (有放回抽樣排列)

permutations 排列  (不放回抽樣排列)

combinations 組合,沒有重複  (不放回抽樣組合)

combinations_with_replacement 組合,有重複  (有放回抽樣組合)

>>

>

import itertools

>>

>

for i in itertools.product(

'abcd'

, repeat =2)

:...

print

(i)...

('a'

,'a')(

'a',

'b')

('a'

,'c')(

'a',

'd')

('b'

,'a')(

'b',

'b')

('b'

,'c')(

'b',

'd')

('c'

,'a')(

'c',

'b')

('c'

,'c')(

'c',

'd')

('d'

,'a')(

'd',

'b')

('d'

,'c')(

'd',

'd')

>>

>

for i in itertools.permutations(

'abcd',2

):..

.print

(i)...

('a'

,'b')(

'a',

'c')

('a'

,'d')(

'b',

'a')

('b'

,'c')(

'b',

'd')

('c'

,'a')(

'c',

'b')

('c'

,'d')(

'd',

'a')

('d'

,'b')(

'd',

'c')

>>

>

for i in itertools.combinations(

'abcd',2

):..

.print

(i)...

('a'

,'b')(

'a',

'c')

('a'

,'d')(

'b',

'c')

('b'

,'d')(

'c',

'd')

>>

>

for i in itertools.combinations_with_replacement(

'abcd',2

):..

.print

(i).

..

(『a』, 『a』) (『a』, 『b』) (『a』, 『c』) (『a』, 『d』) (『b』, 『b』) (『b』, 『c』) (『b』, 『d』) (『c』, 『c』) (『c』, 『d』) (『d』, 『d』)

還有就是,combinations和permutations返回的是物件位址,原因是在python3裡面,返回值已經不再是list,而是iterators(迭代器), 所以想要使用,只用將iterator 轉換成list 即可, 還有其他一些函式返回的也是乙個物件,需要list轉換,比如 list(map())等 。

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...