Reputation: 189786
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]
Upvotes: 2
Views: 240
Reputation: 735
from itertools import chain
def permshift(n,k):
return chain(xrange(1,k+1), [0], xrange(k+1,n))
Upvotes: 0
Reputation: 11173
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))
Upvotes: 1
Reputation: 9578
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)
Upvotes: 1
Reputation: 9323
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:]
Upvotes: 2
Reputation: 70602
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
Upvotes: 4