title: Optimizing permutation generator where total of each permutation totals to same value
body: <p>I'm wanting to create a list of permutations or cartesian products (not sure which one applies here) where the sum of values in each permutation totals to a provided value.</p>
  <p>There should be three parameters required for the function.</p>
  <ol>
  <li><strong>Sample Size:</strong> The number of items in each permutation</li>
  <li><strong>Desired Sum:</strong> The total that each permutation should add up to</li>
  <li><strong>Set of Numbers:</strong> The set of numbers that can be included with repetition in the permutations</li>
  </ol>
  <p>I have an implementation working below but it seems quite slow I would prefer to use an iterator to stream the results but I would also need a function that would be able to calculate the total number of items that the iterator would produce.</p>
  <pre class="lang-py prettyprint-override"><code>def buildPerms(sample_size, desired_sum, set_of_number):
      blank = [0] * sample_size
      return recurseBuildPerms([], blank, set_of_number, desired_sum)
  
  def recurseBuildPerms(perms, blank, values, desired_size, search_index = 0):
      for i in range(0, len(values)):
          for j in range(search_index, len(blank)):
              if(blank[j] == 0):
                  new_blank = blank.copy()
                  new_blank[j] = values[i]
                  remainder = desired_size - sum(new_blank)
                  new_values = list(filter(lambda x: x &lt;=  remainder, values))
                  if(len(new_values) &gt; 0):
                      recurseBuildPerms(perms, new_blank, new_values, desired_size, j)
                  elif(sum(new_blank) &lt;= desired_size):
                      perms.append( new_blank)
      return perms
  
  perms = buildPerms(4, 10, [1,2,3])
  print(perms)
  ## Output
  [[1, 3, 3, 3], [2, 2, 3, 3], [2, 3, 2, 3], 
   [2, 3, 3, 2], [3, 1, 3, 3], [3, 2, 2, 3], 
   [3, 2, 3, 2], [3, 3, 1, 3], [3, 3, 2, 2], 
   [3, 3, 3, 1]]
  
  
  </code></pre>
  <p><a href="https://www.online-python.com/9cmOev3zlg" rel="nofollow noreferrer">https://www.online-python.com/9cmOev3zlg</a></p>
  <p>Questions:</p>
  <ol>
  <li>Can someone help me convert my solution into an iterator?</li>
  <li>Is it possible to have a calculation to know the total number of items without seeing the full list?</li>
  </ol>