此代码有效,但我相信它可以更简单,也允许包含额外的部分,而不必在嵌套循环中添加行的麻烦。怎么样?
#--------------------------------------------------------------------------- ----
# Name: TotalweightCombination
# Purpose: Combine weight/length/etc of pieces to get a sum as close as possible to optSum. Maximally 6 pieces allowed in the resulting combination.
#-------------------------------------------------------------------------------
pieces=[31.75,12.5,28.9,20.95,31.5,13.8,13.95,11.2,32.9,16.6,8.6,17.85]
print("Sum weight pieces:",sum(pieces))
numpieces=len(pieces)
pieces.append(0) # We include a piece with weight 0 to allow combinations with fewer than 6 pieces
optSum=142
bestDiff=1000
totCheck=0
for i,iv in enumerate(pieces):
for j,jv in enumerate(pieces):
if jv==0 or j!=i:
for k,kv in enumerate(pieces):
if kv==0 or k not in [i,j]:
for l,lv in enumerate(pieces):
if lv==0 or l not in [i,j,k]:
for m,mv in enumerate(pieces):
if mv==0 or m not in [i,j,k,l]:
for n,nv in enumerate(pieces):
if nv==0 or n not in [i,j,k,l,m]:
totCheck+=1
theList=[iv,jv,kv,lv,mv,nv]
diff=abs(sum(theList)-optSum)
if diff<bestDiff:
bestDiff=diff
chosen=theList
print("New best sum: %s with "%sum(chosen),chosen)
theTotal=sum(chosen)
print("We try to obtain the sum %s with %s pieces. Checked %s combinations. Best combination: %s gives theTotal %s. Deviation %.4f%%."%(optSum,numpieces,totCheck,[i for i in chosen if i!=0],theTotal,100*(theTotal/optSum-1)))
(编辑:更正了一些标签错误)
答案 0 :(得分:1)
您应该使用combinations()模块中的itertools。
from itertools import combinations
for theList in combinations(pieces, 6)):
# theList stands here for exactly the same as in your most inner loop.
# Do whatever you want with it here