Python2.7實現笛卡爾積N個數組的排列組合

python2.7實現笛卡爾積進行N個數組的排列組合

說明:本人前段時間遇到的求n個數組的所有排列組合的問題,發現笛卡爾積算法可以解決,但是網上搜索的只有Java版本的實現,於是自己試着用python實現,由於新手代碼不太規範。

代碼:本人封裝了一個類Cartesian(笛卡爾),其中封裝了變量和方法:

1.變量
datagroup : 表示n個list(python 中的list與其他編程中的數組定義類似)的集合,即一個二維數組
counterIndex:datagroup反向下標值
counter : 用來記錄當前datagroup中每一個數組輸出的下標,初始全爲0,因爲從第一個開始輸出


2.方法
countlength : 計算數組長度,即計算n的具體值
handle :處理datagoroup二維數組中每一個一維數組輸出的下標值
assemble : 對datagoroup中的n個一維數組中的每一元素進行排列組合輸出


# -*- coding:utf-8 -*-

# python 實現N個數組的排列組合(笛卡爾積算法)
class Cartesian():
    # 初始化
    def __init__(self, datagroup):
        self.datagroup = datagroup
        # 二維數組從後往前下標值
        self.counterIndex = len(datagroup)-1
        # 每次輸出數組數值的下標值數組(初始化爲0)
        self.counter = [0 for i in range(0, len(self.datagroup))]

    # 計算數組長度
    def countlength(self):
        i = 0
        length = 1
        while(i < len(self.datagroup)):
            length *= len(self.datagroup[i])
            i += 1
        return length

    # 遞歸處理輸出下標
    def handle(self):
        # 定位輸出下標數組開始從最後一位遞增
        self.counter[self.counterIndex]+=1
        # 判斷定位數組最後一位是否超過長度,超過長度,第一次最後一位已遍歷結束
        if self.counter[self.counterIndex] >= len(self.datagroup[self.counterIndex]):   

            # 重置末位下標
            self.counter[self.counterIndex] = 0
            # 標記counter中前一位
            self.counterIndex -= 1
            # 當標記位大於等於0,遞歸調用
            if self.counterIndex >= 0:
                self.handle()
            # 重置標記
            self.counterIndex = len(self.datagroup)-1

    # 排列組合輸出
    def assemble(self):
        length = self.countlength()
        i = 0
        while(i < length):
            attrlist = []
            j = 0
            while(j<len(self.datagroup)):
                attrlist.append(self.datagroup[j][self.counter[j]])
                j += 1
            print attrlist
            self.handle()
            i += 1

測試:

注:測試代碼中我只選取了長度爲3的二維數組

if __name__ == "__main__":
    # 構造二維數組
    datagroup = [['aa1', ], ['bb1', 'bb2'], ['cc1', 'cc2', 'cc3']]
    # 創建cartesian對象
    cartesian = Cartesian(datagroup)
    cartesian.assemble()

輸出結果:

數組排列組合輸出

備註:此算法實現用python2.7版本

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章