Created
November 10, 2019 22:21
-
-
Save taiypeo/88e8850f79c1ed96fa6224a9f352b134 to your computer and use it in GitHub Desktop.
Permutation class for my linear algebra course
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Permutation: | |
def __init__(self, perm_list): | |
self.perm_list = perm_list | |
self.n = len(perm_list) | |
def __repr__(self): | |
return ( | |
' '.join([str(i) for i in range(1, self.n + 1)]) + | |
'\n' + | |
' '.join([str(i) for i in self.perm_list]) | |
) | |
def power(self, p): | |
perm_list = self.perm_list[:] | |
for _ in range(p - 1): | |
new_perm_list = [0] * self.n | |
for i in range(self.n): | |
new_perm_list[i] = perm_list[self.perm_list[i] - 1] | |
self.perm_list = new_perm_list | |
return self | |
def inverse(self): | |
new_perm_list = [0] * self.n | |
for i in range(self.n): | |
new_perm_list[self.perm_list[i] - 1] = i + 1 | |
self.perm_list = new_perm_list | |
return self | |
@staticmethod | |
def mul(perm_left, perm_right): | |
perm_list = [0] * perm_right.n | |
for i in range(perm_right.n): | |
index_for_left = perm_right.perm_list[i] - 1 | |
perm_res = perm_left.perm_list[index_for_left] | |
perm_list[i] = perm_res | |
return Permutation(perm_list) | |
def __eq__(self, other): | |
return self.perm_list == other.perm_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment