It looks like you are confusing two concepts: strings that represent finite field polynomials and objects of the class gf2pim, which also represents finite field polynomials. You should instantiate a gf2pim object for each polynomial you wish to manipulate, and the operations on gf2pim objects should return other gf2pim objects. Currently you are trying to use the + operator on 2 strings, which is why your __add__
method is not being called. There are also several other problems with your definition of the gf2pim class. I've refactored your code a bit below, although it is still not perfect. I also left out the division methods, but I think what I did should get you on the right track. See section 3.4.8 of this link for more special method names for operator overloading.
import re
class gf2pim(object):#Your classes should generally inherit from object
def __init__(self, binary):
'''__init__ is a standard special method used to initialize objects. Here __init__
will initialize a gf2pim object based on a binary representation.'''
self.bin = binary
@classmethod
def from_string(cls, string):
return cls(cls._string_to_binary(string))
def to_string(self):
raw = "{0:b}".format(self.bin); raw = str(raw[::-1]); g = [] #reverse binary string for enumeration
g = [i for i,c in enumerate(raw) if c == '1']
processed = "x**"+" + x**".join(map(str, g[::-1]))
if len(g) == 0: return 0 #return 0 if list empty
return processed #returns result in gf(2) polynomial form
@classmethod
def id(cls, lst):
"""returns modulus 2 (1,0,0,1,1,....) for input lists"""
return [int(lst[i])%2 for i in range(len(lst))]
@classmethod
def _list_to_int(self, lst):
"""converts list to integer for later use"""
result = self.id(lst)
return int(''.join(map(str,result)))
@classmethod
def _string_to_list(cls, string):
"""performs regex on raw string and converts to list"""
c = [int(i.group(0)) for i in re.finditer(r'\d+', string)]
return [1 if x in c else 0 for x in xrange(max(c), -1, -1)]
@classmethod
def _string_to_binary(cls, string):
"""converts to base 2; bina,binb are binary values like 110100101100....."""
x = cls._string_to_list(string)
a = cls._list_to_int(x)
bina = int(str(a),2)
return bina #
def __add__(self,other):
"""
__add__ is another special method, and is used to override the + operator. This will only
work for instances of gf2pim and its subclasses.
a,b are GF(2) polynomials like x**7 + x**3 + x**0 ...; returns binary string"""
return gf2pim(self.bin^other.bin)
def __sub__(self,other):
"""
__sub__ is the special method for overriding the - operator
same as addition in GF(2)"""
return self.add(other)
def __str__(self):
return self.to_string()
if __name__ == '__main__':
a = gf2pim.from_string("x**14 + x**1 + x**0")
b = gf2pim.from_string("x**6 + x**2 + x**1")
smadd1 = a+b
print "smadd1 ",smadd1