python非遞迴全排列

來源:互聯網
上載者:User

標籤:res   n個元素   span   array   str   合數   pytho   int   log   

剛剛開始學習python,按照廖雪峰的網站看的,當前看到了函數這一節。結合數組操作,寫了個非遞迴的全排列產生。原理是插入法,也就是在一個有n個元素的已有排列中,後加入的元素,依次在前,中,後的每一個位置插入,產生n+1個新的全排列。因為Python切割數組或者字串,以及合并比較方便,所以,程式會節省很多代碼。

 1 def getArrayInsertCharToStr(STR,CHAR): 2     arr =[] 3     s_len = len(STR) 4     index =0 5     while index <= s_len: 6         #分割字串 7         arr.append(STR[:index]+CHAR+STR[index:s_len]) 8         index = index + 1 9     return arr    10 11 def getArrayInsertCharToArray(array,CHAR):12     index = 013     re_array = []14     while index < len(array):15         re_array = re_array + getArrayInsertCharToStr(array[index],CHAR)16         index = index + 117     return re_array             18 19 def getPermutation(STR):20         resultArr = [STR[0]]21         for item in STR[1:]:22             resultArr = getArrayInsertCharToArray(resultArr,item)23         return     resultArr24 25 26 print(getPermutation(‘abc‘))    

 

python非遞迴全排列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.