Skip to content

Instantly share code, notes, and snippets.

@P403n1x87
Created November 7, 2022 12:25
Show Gist options
  • Save P403n1x87/0252e75d2e5d26e33b9e76f6ae9dcc4c to your computer and use it in GitHub Desktop.
Save P403n1x87/0252e75d2e5d26e33b9e76f6ae9dcc4c to your computer and use it in GitHub Desktop.
Elements of a free module over a ring
class Map(dict):
"""Element of a free module over a ring."""
def __add__(self, other):
m = Map(self)
for k, v in other.items():
n = m.setdefault(k, v.__class__()) + v
if not n and k in m:
del m[k]
continue
m[k] = n
return m
def __mul__(self, other):
m = Map(self)
for k, v in self.items():
n = v * other
if not n and k in m:
del m[k]
continue
m[k] = n
return m
def __rmul__(self, other):
return self.__mul__(other)
def __sub__(self, other):
return self + (-other)
def __neg__(self):
m = Map(self)
for k, v in m.items():
m[k] = -v
return m
def supp(self):
return set(self.keys())
f = Map({"a": 2, "b": 4})
g = Map({"b": 4, "c": 4})
print("f =", f)
print("g =", g)
print("f + g = ", f + g)
print("f - g = ", f - g)
print("supp(f - g) = ", (f - g).supp())
print("f * 2 =", f * 2)
print("2 * f =", 2 * f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment