Issue
I need a python functional (a function that creates functions), which creates all cyclic permutation operators for a list of length N.
For a python list a (e.g. a = [1, 2, 3, 4,5,6], N= 6
), one can define a function
def cyclic_perm(a):
n = len(a)
b = [[a[i - j] for i in range(n)] for j in range(n)]
return b
that gives you all the possible, cyclic permutations of a list, in this case 6 lists.
I would like the function to give me not the list, but (in this case) 6 operators, that ,when applied to the list, each give one of the permuted lists.
Solution
I am not too sure what the goal of this exercise is, but you can do this with partial functions.
from functools import partial
def reorder_from_idx(idx, a):
return a[idx:] + a[:idx]
def cyclic_perm(a):
return [partial(reorder_from_idx, i) for i in range(len(a))]
a = [1, 2, 3, 4, 5, 6]
result = cyclic_perm(a)
print(result)
#[functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 0),
# functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 1),
# functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 2),
# functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 3),
# functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 4),
# functools.partial(<function reorder_from_idx at 0x00000298D92189D8>, 5)]
result[3](a)
#[4, 5, 6, 1, 2, 3]
Answered By - Paritosh Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.