求解列表中元素的排列和組合問題這個問題之前就遇到過幾次沒有太留意,最近在做題的時候遇上挺多的排列組合問題的,想來有必要溫習一下了,今天花點時間寫一下,之前都是手工寫的,后來知道可以直接使用python的內置模塊就可以完成這個工作了,今天就使用python的itertools模塊來完成這個工作,一共解決四個問題:
1.生成排列,列表中元素不允許重復出現
2.生成排列,列表中元素可以重復出現
3.生成組合,不限元素個數,列表中元素不允許重復出現
4.生成組合,不限元素個數,列表中元素可以重復出現
因為大家都有排列組合的知識這里就不累贅了,問題很簡單,下面看具體的實現:
#!usr/bin/env python #encoding:utf-8 ''''' __Author__:沂水寒城 功能:求解列表中元素的排列和組合問題 ''' from itertools import product from itertools import combinations import itertools def test_func1(num_list): ''''' 生成排列 列表中元素不允許重復出現 排列數計算為:n!,其中n為num_list列表中元素個數 ''' tmp_list = itertools.permutations(num_list) res_list=[] for one in tmp_list: res_list.append(one) print res_list print '元素不允許重復出現排列總數為:', len(res_list) def test_func11(num_list): ''''' 生成排列 列表中元素可以重復出現 排列總數計算為:(n*n*n...*n),一共n個n相乘 ''' num=len(num_list) res_list=list(product(num_list,repeat=num)) print res_list print '元素可以重復出現排列總數為:', len(res_list) def test_func2(num_list): ''''' 生成組合,不限元素個數 列表中元素不允許重復出現 組合數計算為:2^n,其中n為num_list列表中元素個數 ''' res_list=[] for i in range(len(num_list)+1): res_list+=list(combinations(num_list, i)) print res_list print '元素不允許重復出現組合總數為:', len(res_list) def test_func22(num_list): ''''' 生成組合,不限元素個數 列表中元素可以重復出現 ''' res_list=[] num_list1=[str(i) for i in num_list] for i in range(0,len(num_list)+1): res_list+=[''.join(x) for x in itertools.product(*[num_list1] * i)] print res_list print '元素可以重復出現組合總數為:', len(res_list) if __name__ == '__main__': num_list=[1,2,3,4] test_func1(num_list) print '-------------------------------------' test_func11(num_list) print '-------------------------------------' test_func2(num_list) print '-------------------------------------' test_func22(num_list)
————————————————
版權聲明:本文為CSDN博主「程序員牡蠣」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/chengxun03/article/details/105498145