2016-10-11 7 views
1

このコードは機能しますが、よりシンプルにすることができ、入れ子になったループに行を追加することなく余分な部分を含めることができます。どうやって?入れ子にされたforループの簡略化

#---------------------------------------------------------------------------  ---- 
# 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))) 

(編集:いくつかのタブのエラーを修正)

答えて

1

あなたはitertoolsモジュールからcombinations()を使用する必要があります。

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 
関連する問題