|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
用python自己的方法 写了一个通过列表,和需要得到的数据,性能比一般的是要快点,数字越大几乎成指数增加,不知道有没有更改的方法,动态规划除外。
- import time
- global prelst
- global prelst
- reslst = []
- prelst = []
- def seachbi(li, val):
- left = 0
- right = len(li)-1
- maxli = li[-1]
- minli = li[0]
- if val>maxli or val<minli:
- return None
- else:
- while left<=right:
- mid = left+(right-left)//2
- if li[mid]==val:
- return mid
- elif li[mid]>val:
- right = mid-1
- else:
- left = mid+1
- else:
- return None
-
- def listSumEqual(prelst, lst, equalsum,num):
- if num ==1:
- if seachbi(lst,equalsum) != None:
- templst = prelst.copy()
- new = lst[seachbi(lst,equalsum)]
- templst.append(new)
- reslst.append(templst)
- elif num == 2:
- for i in range(len(lst)-1):
- templst = prelst.copy()
- templst.append(lst[i])
- equalsuma = equalsum - sum(templst)
- seresult = seachbi(lst[i+1:],equalsuma)
- if seresult != None:
- new = lst[i+1:][seachbi(lst[i+1:],equalsuma)]
- templst.append(new)
- reslst.append(templst)
- else:
- break
- else:
- for i in range(len(lst)-num+1):
- prelst.append(lst[i])
- listSumEqual(prelst, lst[i+1:], equalsum, num-1)
- prelst.pop()
- # return reslst
- def filterlst(lst,sum):
- for i in range(len(lst)):
- if lst[i] > sum:
- return lst[:i]
- if __name__ == "__main__":
- lst = list(range(1,100,1))
- equalsum = int(input("Please input Sum Number:"))
- t1 = time.time()
- lst = filterlst(lst,equalsum)
- length = len(lst)
- for num in range(1,length):
- if sum(lst[:num]) > equalsum:
- print("no match data")
- break
- else:
- prelst = []
- listSumEqual(prelst, lst, equalsum, num)
- t2 = time.time()
- print("It cost %s second time!"%(t2-t1))
-
复制代码
但这个比使用intertools.combinations 是要快100倍以上!
- from time import time
- from itertools import combinations
- lst = list(range(1,100))
- num = int(input("Please input sum data:"))
- lstfilter = list(filter(lambda x:x<=num,lst))
- t1 = time()
- res = []
- for r in range(len(lstfilter)):
- bn = combinations(lst, r)
- for b in bn:
- if sum(b)==30:
- if b not in res:
- res.append(b)
- t2 = time()
- print("it cost %s time"%(t2-t1))
复制代码 |
|