2016-10-11 6 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))) 

(편집 : 수정 일부 탭 오류) 당신은 itertools 모듈에서 combinations()를 사용해야합니다

답변

1

.

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