Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
eval solution in Creative category for Simplification by Sim0000
from collections import Counter
class Poly:
def __init__(self, d):
self.v = Counter(d.v if isinstance(d, Poly) else d)
def __add__(self, d):
if isinstance(d, int): d = Poly({0:d})
new = Poly(self)
for i in d.v.keys(): new.v[i] += d.v[i] # new += d
return new
__radd__ = __add__
def __sub__(self, d):
if isinstance(d, int): d = Poly({0:d})
new = Poly(self)
for i in d.v.keys(): new.v[i] -= d.v[i] # new -= d
return new
def __rsub__(self, d):
return Poly(Counter({0:d})) - self
def __mul__(self, d):
if isinstance(d, int): d = Poly({0:d})
t = Counter()
# t = self * d
for i in self.v.keys():
for j in d.v.keys(): t[i + j] += self.v[i] * d.v[j]
return Poly(t)
__rmul__ = __mul__
def __neg__(self):
new = Poly(self)
for i in new.v.keys(): new.v[i] = -new.v[i] # neg
return new
def __str__(self):
e = self.v
s = ['+' + str(e[i]) + '*x'*(i>0) + ('**'+str(i))*(i>1) for i in sorted(e.keys(), reverse=True) if e[i]]
return ''.join(s).replace('+1*', '+').replace('-1*', '-')[1:].replace('+-', '-') or '0'
def simplify(expr):
x = Poly({1:1})
return str(eval(expr))
# class Poly and eval
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert simplify("(x-1)*(x+1)") == "x**2-1", "First and simple"
assert simplify("(x+1)*(x+1)") == "x**2+2*x+1", "Almost the same"
assert simplify("(x+3)*x*2-x*x") == "x**2+6*x", "Different operations"
assert simplify("x+x*x+x*x*x") == "x**3+x**2+x", "Don't forget about order"
assert simplify("(2*x+3)*2-x+x*x*x*x") == "x**4+3*x+6", "All together"
assert simplify("x*x-(x-1)*(x+1)-1") == "0", "Zero"
assert simplify("5-5-x") == "-x", "Negative C1"
assert simplify("x*x*x-x*x*x-1") == "-1", "Negative C0"
Sept. 10, 2014
Comments: