1. 程式人生 > >python自帶的排列組合函式

python自帶的排列組合函式

需求: 在你的面前有一個n階的臺階,你一步只能上1級或者2級,請計算出你可以採用多少種不同的方法爬完這個樓梯?輸入一個正整數表示這個臺階的級數,輸出一個正整數表示有多少種方法爬完這個樓梯。

分析:提煉出題乾的意思:用1和2產生不同組合,使得他們的和等於臺階的級數,輸出有多少種組合方式。

解決: 主要的問題就是如何利用1和2產生不同的組合,查閱了python關於排列組合相關的資料

  最後發現了一個強大的python庫 itertools

介紹一下常用的幾個函式:

  itertools.product(sequence,repeat)   #從sequence中拿出repeat個數做排列

(repeat關鍵字傳參) 有放回的拿出  repeat與sequence的長度無關。

demo: 輸出為型別為元組,

In [2]: import itertools

In [3]: for i in itertools.product([1,2],repeat= 1):
   ...:     print(i)
   ...:     
   ...: 
(1,)
(2,)

In [4]: for i in itertools.product([1,2],repeat= 2):
   ...:     print(i)
   ...:     
   ...: 
(1, 1)
(1, 2)
(2, 1)
(2, 2)

In [5]: for i in itertools.product([1,2],repeat= 3):
    ...:     print(i)
    ...:     
    ...: 
(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)

  itertools.permutations(sequence,n)  #  從sequence中拿出n個數做排列, 不放回的拿出, n 只能小於等於sequence的長度 否則沒有輸出。

demo:

In [6]: for i in itertools.permutations([1,2], 1):
   ...:     print(i)
   ...:     
   ...: 
(1,)
(2,)

In [7]: for i in itertools.permutations([1,2], 2):
   ...:     print(i)
   ...:     
   ...: 
(1, 2)
(2, 1)

In [8]: for i in itertools.permutations([1,2],3):
   ...:     print(i)
   ...:     
   ...: 

In [9]: 

itertools.combinations(sequence, n )   # 從sequence中選n個數做組合,相當於不放回, 當n 大於sequence的長度自然沒有資料。

demo:

In [10]: for i in itertools.combinations([1,2],1):
    ...:     print(i)
    ...:     
    ...: 
(1,)
(2,)

In [11]: for i in itertools.combinations([1,2],2):
    ...:     print(i)
    ...:     
    ...: 
(1, 2)

In [12]: for i in itertools.combinations([1,2],3):
    ...:     print(i)
    ...:     
    ...: 

In [13]: 

itertools.combinations_with_replacement(sequence, n )  # 從sequence中選n個數做組合,允許元素重複,repeat與sequence的長度無關。 

demo:

In [14]: for i in itertools.combinations_with_replacement([1,2],1):
    ...:     print(i)
    ...:     
    ...: 
(1,)
(2,)

In [15]: for i in itertools.combinations_with_replacement([1,2],2):
    ...:     print(i)
    ...:     
    ...: 
(1, 1)
(1, 2)
(2, 2)

In [16]: for i in itertools.combinations_with_replacement([1,2],3):
    ...:     print(i)
    ...:     
    ...: 
(1, 1, 1)
(1, 1, 2)
(1, 2, 2)
(2, 2, 2)

In [17]: for i in itertools.combinations_with_replacement([1,2],4):
    ...:     print(i)
    ...:     
    ...: 
(1, 1, 1, 1)
(1, 1, 1, 2)
(1, 1, 2, 2)
(1, 2, 2, 2)
(2, 2, 2, 2)

回到咱們的問題, 在這幾個函式中,選擇一個,很明顯 itertools.product(sequence,repeat)  符合我們的要求:

code:

  1 import itertools
  2 n = int(input("輸入臺階數:"))
  3 l = [1,2] # 或者"12",序列即可
  4 m = 0  # 組合數
  5 for i in range(1,n+1):
  6     for j in itertools.product(l,repeat = i):
  7         asum = 0
  8         for k in j:
  9             asum += k # 累加步數 
 10         if asum == n: # 判斷條件 步數等於臺階數
 11              m += 1  # 組合數加1
 12 print("總的組合數:{}".format(m)) 
 13 

bash:

[email protected]:~$ python3 demo.py 
輸入臺階數:1
總的組合數:1
[email protected]:~$ python3 demo.py 
輸入臺階數:2
總的組合數:2
[email protected]:~$ python3 demo.py 
輸入臺階數:3
總的組合數:3
[email protected]:~$ python3 demo.py 
輸入臺階數:4
總的組合數:5
[email protected]:~$ python3 demo.py 
輸入臺階數:5
總的組合數:8
[email protected]:~$ python3 demo.py 
輸入臺階數:6
總的組合數:13
[email protected]:~$ python3 demo.py 
輸入臺階數:7
總的組合數:21
[email protected]:~$ 

功能倒是實現了, 但是效率確實不咋地, 臺階數上20就得花點時間了。

import requests
import itertools
import json
import threading
import time
class IDCMinterface():  
    def getassetsrecordpagelist(self,p):
        url=''
        header = {'Content-Type': 'application/json; charset=UTF-8',
                  'Accept': 'application/json;text/plain',
                  'Accept-Encoding':'gzip',
                  'Connection':'keep-alive',
                  'Content-Length':'400'}
        #arg={"AssetsRecordType":'',"AssetsID":'',"StartDate":'',"EndDate":'',"BillNO":'',"PageSize":10, "PageIndex":1, "clientType":"undefined"}
        dat=requests.post(url,headers=header,data=p)
        dat=dat.json()
        #print(dat['status'])
        if dat['status']!=105:
            print(dat)
            print(p)

if __name__=='__main__':
    #Requestss().gettoken()
    num=0
    A = [{"serial_number":num,"phrase":"junior"},{"serial_number":num,"phrase":"onion"},{"serial_number":num,"phrase":"detail"}]
    B = [{"serial_number": num, "phrase": "emerge"}, {"serial_number": num, "phrase": "weapon"}, {"serial_number": num, "phrase": "robust"}]
    C = [{"serial_number": num, "phrase": "isolate"}, {"serial_number": num, "phrase": "volcano"}, {"serial_number": num, "phrase": "rally"}]
    D = [{"serial_number": num, "phrase": "private"}, {"serial_number": num, "phrase": "detect"}, {"serial_number": num, "phrase": "become"}]
    hw=[A,B,C,D]
    helpword = ['license', 'agent','close', 'wine', 'field', 'wide', 'steak',  'tell', 'text', 'deal', 'pole','purity']
    print(time.strftime("%Y-%m-%d %H:%M:%S"))
    p=0
    for i in itertools.permutations(hw,4):
        # i=str(i)
        # print(i)
        # i=i.replace('], [',',').replace("([",'[').replace("])",']').replace('}, {','}, ,{').replace('[','').replace(']','')
        # print(type(i),i)
        # i=i.split(', ,')
        # print(type(i),i)
        num=0
        word=[]
        for m in range(0,4):
            for n in range(1,4):
                num=num+1
                #print(i[m][n-1]['serial_number'])
                #print(i[0])
                i[m][n-1]['serial_number']=num
                word.append(i[m][n-1])
                #print(i)
        #print(help)
        i=list(word)
        i=json.dumps(i) #或者post方法的data直接改為json
        #print(i[0])
        p = p + 1
        IDCMinterface().getassetsrecordpagelist(i)