2012-06-20 5 views
2

아래의 중첩 루프를 단순화하는 방법이 있는지 궁금합니다. 문제는 각 루프의 반복자가 이전 루프의 내용에 의존한다는 것입니다.Python : 중첩 된 FOR 루프를 단순화 하시겠습니까?

# Find the number of combinations summing to 200 using the given list of coin 

coin=[200,100,50,20,10,5,2,1] 

total=[200,0,0,0,0,0,0,0] 
# total[j] is the remaining sum after using the first (j-1) types of coin 
# as specified by i below 

count=0 
# count the number of combinations 

for i in range(int(total[0]/coin[0])+1): 
    total[1]=total[0]-i*coin[0] 
    for i in range(int(total[1]/coin[1])+1): 
     total[2]=total[1]-i*coin[1] 
     for i in range(int(total[2]/coin[2])+1): 
      total[3]=total[2]-i*coin[2] 
      for i in range(int(total[3]/coin[3])+1): 
       total[4]=total[3]-i*coin[3] 
       for i in range(int(total[4]/coin[4])+1): 
        total[5]=total[4]-i*coin[4] 
        for i in range(int(total[5]/coin[5])+1): 
         total[6]=total[5]-i*coin[5] 
         for i in range(int(total[6]/coin[6])+1): 
          total[7]=total[6]-i*coin[6] 
          count+=1 

print count 
+0

도 참조 [ "반복적으로 지정된 양을 생산하고 모든 동전의 조합을 찾아"] (http://stackoverflow.com/q/9815077/90527), [ "숙제 질문 및 답변 방법]"(http://meta.stackexchange.com/q/10811/). – outis

+2

당신의 문제는 네 스티드 루프를 간소화하는 것이 아니라 똑똑한 알고리즘을 가져야합니다. – xvatar

+0

@outis - 숙제 일지라도 약간 짜증이납니다.하지만 여기에는 약간의 노력이 있습니다. 제약 라이브러리가 조금 있을지도 모릅니다. 어쨌든 까다 롭습니다 ... –

답변

1
  1. 모든 int 캐스팅을 제거 할 수 있습니다. int/int는 파이썬, 즉 정수 나누기에서 여전히 int입니다.

  2. 는이 청소 것 재귀처럼 보이는 nicly

    count = 0 
    coin=[200,100,50,20,10,5,2,1] 
    total=[200,0,0,0,0,0,0,0] 
    
    def func(i): 
        global count,total,coin 
        for x in range(total[i-1]/coin[i-1]+1): 
         total[i]=total[i-1]-x*coin[i-1] 
         if (i == 7): 
          count += 1 
         else: 
          func(i+1) 
    

    FUNC (1) 인쇄 수

+0

'/'는 Python3에서 부동 구분이되었습니다. 파이썬 2와 파이썬 3에서 똑같이 작동하는 것처럼 int division을 원한다면'/ /'를 사용하는 것이 더 낫습니다. –

+0

@gnibbler 아아아, 파이썬 3을 피했습니다. 얼마나 많은 변화가 있었는지 고민했습니다. 하지만 적어도 지금은 ** :-)처럼 들리는 것을 피할 수 있습니다. – 8bitwide

2

내가 http://labix.org/python-constraint 보는 것이 좋습니다 파이썬 제약 라이브러리입니다 : 여기에 코드입니다. 예제 파일 중 하나는 실제로 특정 금액에 도달하는 주화의 순열이며, 일단 규칙을 지정하면이를 처리합니다.

+0

[coins.py] (http://codespeak.net/svn/user/niemeyer/constraint/trunk/examples/coins/coins.py) – jfs

+0

@JFSebastian 그게 –

+1

이겠지만 모든 해결책이 열거되어 있습니다. 동적 프로그래밍을 사용하여 계산하는 것보다 효과적이지 않음 – jfs

0
combinations = set() 
for i in range(len(coins)): 
    combinations = combinations | set(for x in itertools.combinations(coins, i) if sum(x) == 200) 
print len(combinations) 

다소 느리지 만 작동해야합니다.

관련 문제