TAGS :Viewed: 13 - Published at: a few seconds ago

[ Making a shift permutation in python ]

I need to make a permutation that looks like a sequence of 1-N with a 0 stuffed in place #k.

This method works, but is there anything simpler using builtin functions?

def permshift(n,k):
   return [0 if x == k else x+(x<k) for x in range(n)]

>>> permshift(7,0)
[0, 1, 2, 3, 4, 5, 6]
>>> permshift(7,1)
[1, 0, 2, 3, 4, 5, 6]
>>> permshift(7,2)
[1, 2, 0, 3, 4, 5, 6]
>>> permshift(7,3)
[1, 2, 3, 0, 4, 5, 6]
>>> permshift(7,4)
[1, 2, 3, 4, 0, 5, 6]
>>> permshift(7,5)
[1, 2, 3, 4, 5, 0, 6]
>>> permshift(7,6)
[1, 2, 3, 4, 5, 6, 0]

Answer 1


Just create a new list, and insert the 0 wherever you need to.

def permshift(n, k):
    lst = range(1, n)
    lst.insert(k, 0)
    return lst

Answer 2


More lines, but I think it's simpler:

def permshift(n, k):
   x = range(1, n)
   x.insert(k, 0)
   return x

Here's an interesting one that's shorter than the most popularly repeated answer:

def permshift(n, k):
   x = range(1, n)
   return x[:k] + [0] + x[k:]

Answer 3


Hehe - it's funny when so many people come up with the same solution

def permshift(n,k):
     r = range(1,n)
     r.insert(k,0)
     return r

For completeness here's a generator expression if you really care about efficiency

def permshift(n,k):
    for i in xrange(1,n):
        yield i
        if i == k:
            yield 0

print list(permshift(7,2))

Answer 4


Good answers already but here's a one line version for kicks and giggles:

permshift = lambda n,k: range(1, k+1) + [0] + range(k+1, n)

Answer 5


from itertools import chain

def permshift(n,k):
    return chain(xrange(1,k+1), [0], xrange(k+1,n))