This gist shows the implementation of a group using python. All of the group axioms are checked by the code.
Created
June 9, 2019 00:07
-
-
Save adamisntdead/6aff31611c29c61d8ba580e7d3f37070 to your computer and use it in GitHub Desktop.
Group Theory in Python
This file contains hidden or 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
import itertools | |
class Group: | |
def __init__(self, G, operation, strict=True): | |
"""Create a group | |
Create a group from the group's set and the | |
corresponding binary operation. Setting strict to False | |
will avoid checking the group axioms, and should be done on | |
very large groups. | |
""" | |
self.G = G | |
self.operation = operation | |
self.id = None | |
if strict: | |
if not self.check_closure(): | |
raise TypeError("The group operation does not obey the closure axiom") | |
if not self.check_associativity(): | |
raise TypeError("The group operation does not obey the associativity axiom") | |
if self.identity() is None: | |
raise TypeError("The group does not have an identity element") | |
if not self.check_inverses(): | |
raise TypeError("Not all elements have inverse elements") | |
def check_closure(self): | |
"""Check the closure axiom. | |
In a group, for all a, b in G, then (a * b) is also | |
in G, where * is the group operation. | |
""" | |
for (a, b) in itertools.product(self.G, repeat=2): | |
if not self.operation(a, b) in self.G: | |
return False | |
return True | |
def check_associativity(self): | |
"""Check the associativity axiom | |
In a group, for all a, b, c in G, then | |
(a * b) * c = a * (b * c), where * is the group operation. | |
""" | |
for (a, b, c) in itertools.product(self.G, repeat=3): | |
if self.operation(self.operation(a, b), c) != self.operation(a, self.operation(b, c)): | |
return False | |
return True | |
def check_inverses(self): | |
"""Check the inverses axiom | |
In a group, for each a in G, there is some element | |
denoted a^-1 or -a, such that (a * a^-1) = e | |
""" | |
id = self.identity() | |
for a in self.G: | |
found = False | |
for b in self.G: | |
if self.operation(a, b) == id: | |
found = True | |
break | |
if not found: | |
return False | |
return True | |
def identity(self): | |
"""Return the groups identity element | |
In a group, ther eis an element e in G such that for every element | |
a in G, the equation (e * a) = (a * e) = a holds. | |
Such an element is unique. | |
""" | |
if self.id is not None: | |
return self.id | |
for a in self.G: | |
nident = 1 | |
for b in self.G: | |
if self.operation(a, b) == b: | |
pass | |
else: | |
nident = 0 | |
break | |
if nident == 1: | |
self.id = a | |
return a | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment