Skip to content

Instantly share code, notes, and snippets.

@yassu
Created March 20, 2016 05:07
Show Gist options
  • Save yassu/d4b321e8c0c2ad20929f to your computer and use it in GitHub Desktop.
Save yassu/d4b321e8c0c2ad20929f to your computer and use it in GitHub Desktop.
class for free groups
#!/usr/bin/env python
# coding: UTF-8
class Character(str):
pass
ONE = (Character('1'), 0)
class Word(list):
# list of pair of Character and power
def __init__(self, l=[]):
list.__init__(self, l)
def simplify(self):
is_recersible = False
now_chara = None
now_power = 0
word = Word()
for (chara, power) in self:
if chara == now_chara:
now_power += power
else:
if now_chara is not None and now_power != 0:
word.append((now_chara, now_power))
elif now_chara is not None and now_power == 0:
is_recersible = True
now_chara = chara
now_power = power
if now_chara is not None and now_power != 0:
word.append((now_chara, now_power))
if is_recersible:
return word.simplify()
elif list(word) == []:
return Word([ONE])
else:
return word
def inverse(self):
word = self[:]
word.reverse()
res = []
for (chara, power) in word:
res.append((chara, power * (-1)))
return Word(res)
def __mul__(self, other):
return Word(self[:] + other[:]).simplify()
def __str__(self):
if len(self.simplify()) == 1 and self[0] == ONE:
return 'unit'
s = ''
for (chara, power) in self:
s += chara
if len(str(power)) == 1:
s += '^' + str(power)
else:
s += '^{' + str(power) + '}'
return s
def __eq__(self, other):
return list(self.simplify()) == list(other.simplify())
if __name__ == '__main__':
w1 = Word([(Character('a'), 1)])
print(w1.inverse().simplify())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment