Generating permutation in Python with specific rule

Posted by twfx on Stack Overflow See other posts from Stack Overflow or by twfx
Published on 2013-06-30T04:17:46Z Indexed on 2013/06/30 4:21 UTC
Read the original article Hit count: 412

Let say a=[A, B, C, D], each element has a weight w, and is set to 1 if selected, 0 if otherwise. I'd like to generate permutation in the below order

1,1,1,1
1,1,1,0
1,1,0,1
1,1,0,0
1,0,1,1
1,0,1,0
1,0,0,1
1,0,0,0

Let's w=[1,2,3,4] for item A,B,C,D ... and max_weight = 4. For each permutation, if the accum weight has exceeded max_weight, stop calculation for that permutation, move to next permutation. For eg.

1,1,1    --> 6 > 4, exceeded, stop, move to next
1,1,1    --> 6 > 4, exceeded, stop, move to next  
1,1,0,1  --> 7 > 4  finished, move to next  
1,1,0,0  --> 3      finished, move to next  
1,0,1,1  --> 8 > 4, finished, stop, move to next
1,0,1,0  --> 4      finished, move to next  
1,0,0,1  --> 5 > 4  finished, move to next  
1,0,0,0  --> 1      finished, move to next  

[1,0,1,0] is the best combination which does not exceeded max_weight 4

My questions are

  1. What's the algorithm which generate the required permutation? Or any suggestion I could generate the permutation?
  2. As the number of element can be up to 10000, and the calculation stop if the accum weight for the branch exceeds max_weight, it is not necessary to generate all permutation first before the calculation. How can the algo in (1) generate permutation on the fly?

© Stack Overflow or respective owner

Related posts about python

Related posts about data-structures