你可以用一个简单的多项式除法来表示一个普通的多项式除法from math import fabs
def poly_div(p1, p2):
def degree(poly):
while poly and poly[-1] == 0:
poly.pop()
return len(poly)-1
p2_degree = degree(p2)
p1_degree = degree(p1)
if p2_degree < 0:
raise ZeroDivisionError
if p1_degree >= p2_degree:
q = [0] * p1_degree
while p1_degree >= p2_degree:
d = [0]*(p1_degree – p2_degree) + p2
mult = q[p1_degree – p2_degree] = p1[-1] / float(d[-1])
d = [coeff*mult for coeff in d]
p1 = [fabs(p1_c – p2_c) for p1_c, p2_c in zip(p1, d)]
p1_degree = degree(p1)
r = p1
else:
q = [0]
r = p1
return q, r
class BinPoly:
def __init__(self, poly):
self.poly = [int(bit) for bit in list(poly)]
def __mod__(self, other):
return poly_div(self.poly, other.poly)
if __name__ == ‘__main__’:
a = BinPoly(‘10011’)
b = BinPoly(‘101’)
print(a%b)
如您所见,您正在用字符串构造多项式,将类调整为使用二进制数应该不会太难,留给读者练习;)