#_*_ coding: UTF-8 _*_
#正整數(shù)N等于M個正整數(shù)之和
import itertools
import sys
import os?
import copy
#參數(shù)說明
#total:表示有多少個數(shù),M
#sum:表示正整數(shù)的和,N
#comb_list:存儲最終輸出的所有列表組合
#tmp_comb_list:臨時最終輸出的所有列表組合
#max_num:當前組合中的最大取值
#num_pos:當前求出的數(shù)值在當前l(fā)ist中保存的位置
def doFindComb(total, sum, comb_list, tmp_comb_list, max_num=1, num_pos=0):
? ? tmp_result = copy.deepcopy(tmp_comb_list)
? ? if(total > sum):
? ? ? ? return
? ? elif(total == sum):
? ? ? ? for i in range(num_pos, total+num_pos):
? ? ? ? ? ? tmp_result[i]=1
? ? ? ? result_data = list(itertools.permutations(tmp_result))
? ? ? ? list_len = len(result_data)
? ? ? ? for i in range(0, list_len):
? ? ? ? ? ? result_data[i] = list(result_data[i])
? ? ? ? for item in result_data:
? ? ? ? ? ? if item not in comb_list:
? ? ? ? ? ? ? ? comb_list.append(item)
? ? ? ? return
? ? elif(total == 1):
? ? ? ? if(sum <= max_num):
? ? ? ? ? ? tmp_result[num_pos]=sum
? ? ? ? ? ? result_data = list(itertools.permutations(tmp_result))
? ? ? ? ? ? list_len = len(result_data)
? ? ? ? ? ? for i in range(0, list_len):
? ? ? ? ? ? ? ? result_data[i] = list(result_data[i])
? ? ? ? ? ? for item in result_data:
? ? ? ? ? ? ? ? if item not in comb_list:
? ? ? ? ? ? ? ? ? ? comb_list.append(item)
? ? ? ? return
? ??
? ? min = int(sum/total)
? ? if(sum % total != 0):
? ? ? ? min = int(sum/total) +1
? ? max = sum-total+1
? ? tmp_list = [0 for x in range(0, total+num_pos)]
? ? for i in range(min, max+1):
? ? ? ? tmp_list = copy.deepcopy(tmp_comb_list)
? ? ? ? tmp_list[num_pos]=i
? ? ? ? doFindComb(total-1, sum-i, comb_list, tmp_list, i, num_pos+1)
'''
comb_list = []
tmp_comb_list = [0 for x in range(0, total)]
total = 5
sum = 20
doFindComb(total, sum, comb_list, tmp_comb_list)
'''
if __name__ == "__main__":
? ? if (len(sys.argv) != 3):
? ? ? ? print("parameter error")
? ? ? ? print("usage: python xxx.py m n")
? ? else:
? ? ? ? total = int(sys.argv[1])
? ? ? ? sum = int(sys.argv[2])
? ? ? ? comb_list = []
? ? ? ? tmp_comb_list = [0 for x in range(0, total)]
? ? ? ? doFindComb(total, sum, comb_list, tmp_comb_list)
? ? ? ? print(comb_list)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
