Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While probably not the most elegant solution, this would work:</p> <pre><code>def f(n, s): def g(n,s): if n == 1: yield (s,) else: for i in xrange(s + 1): for j in g(n - 1,s - i): yield (i,) + j L = list(g(3, 5)) D = [] i = 1 while i != len(L): for j in xrange(len(L[i])): if abs(L[i][j] - L[i-1][j]) &gt; 1: D.append(L.pop(i)) i -= 1 break for d in D: ins = True for j in xrange(len(L[-1])): if abs(L[-1][j] - d[j]) &gt; 1: ins = False break if ins: L.append(d) D.remove(d) i += 1 return L for i in f(3, 5): print i </code></pre> <p>This prints:</p> <pre><code>(0, 0, 5) (0, 1, 4) (0, 2, 3) (0, 3, 2) (0, 4, 1) (0, 5, 0) (1, 4, 0) (2, 3, 0) (3, 2, 0) (4, 1, 0) (5, 0, 0) (4, 0, 1) (3, 0, 2) (2, 0, 3) (1, 0, 4) (1, 1, 3) (2, 1, 2) (3, 1, 1) (2, 2, 1) (1, 2, 2) (1, 3, 1) </code></pre> <p>It basically defines <code>g</code> inside of <code>f</code>, as the generator to create the permuations. It then goes through the list of that and checks for each element if the difference (the <code>abs</code> part) between the element in the one sub-list and the one before (not explained very well, I know... But you get it) is greater than 1, and if so removes that list, appends it to <code>D</code> and reduces the index by 1 (which is why I used <code>while</code> instead of <code>for</code>).</p> <p><strong>Edit:</strong> After every check of an element, it goes through <code>D</code> and sees if anything fits to <code>L</code>, and if so, appends it.</p> <p>It then returns the filtered list.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload