Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating cyclic permutations / reduced Latin Squares in Python
    text
    copied!<p>Was just wondering what's the most efficient way of generating all the cyclic permutations of a list in Python. In either direction. For example, given a list <code>[1, 2, 3, 4]</code>, I want to generate either:</p> <pre><code>[[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] </code></pre> <p>where the next permutation is generated by moving the last element to the front, or:</p> <pre><code>[[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] </code></pre> <p>where the next permutation is generated by moving the first element to the back.</p> <p>The second case is slightly more interesting to me because it results in a reduced Latin square (the first case also gives a Latin square, just not reduced), which is what I'm trying to use to do experimental block design. It actually isn't that different from the first case since they're just re-orderings of each other, but order does still matter.</p> <p>The current implementation I have for the first case is:</p> <pre><code>def gen_latin_square(mylist): tmplist = mylist[:] latin_square = [] for i in range(len(mylist)): latin_square.append(tmplist[:]) tmplist = [tmplist.pop()] + tmplist return latin_square </code></pre> <p>For the second case its:</p> <pre><code>def gen_latin_square(mylist): tmplist = mylist[:] latin_square = [] for i in range(len(mylist)): latin_square.append(tmplist[:]) tmplist = tmplist[1:] + [tmplist[0]] return latin_square </code></pre> <p>The first case seems like it should be reasonably efficient to me, since it uses <code>pop()</code>, but you can't do that in the second case, so I'd like to hear ideas about how to do this more efficiently. Maybe there's something in <code>itertools</code> that will help? Or maybe a double-ended queue for the second case?</p>
 

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