Skip to content

Instantly share code, notes, and snippets.

@tinkerstudent
Last active September 24, 2016 20:30
Show Gist options
  • Select an option

  • Save tinkerstudent/e075abde1660c7e8662008153bb38738 to your computer and use it in GitHub Desktop.

Select an option

Save tinkerstudent/e075abde1660c7e8662008153bb38738 to your computer and use it in GitHub Desktop.
class Equation:
def __init__(self, terms, coeffs):
self.terms = terms
self.coeffs = coeffs
def __str__(self):
result = ''
for i in range(0, len(self.terms)):
if self.coeffs[i] > 0:
if i == 0:
result = result + str(self.coeffs[i])
else:
result = result + ' + ' + str(self.coeffs[i])
elif self.coeffs[i] < 0:
result = result + ' - ' + str(abs(self.coeffs[i]))
result = result + self.terms[i]
return result
def multiply(self, eqn):
rterms = []
for t1 in self.terms:
t1 = self.unbox(t1)
for t2 in eqn.terms:
t2 = self.unbox(t2)
t = t1 + t2
t = ''.join(sorted(t))
t = self.box(t)
rterms.append(t)
rcoeffs = []
for c1 in self.coeffs:
for c2 in eqn.coeffs:
c = c1 * c2
rcoeffs.append(c)
result = Equation(rterms, rcoeffs)
return result
def coeff(self, term):
result = 0
for t in range(0, len(self.terms)):
if self.terms[t] == term:
result = result + int(self.coeffs[t])
return result
def box(self, term):
result = ''
count = 0
char = ''
for i in range(0, len(term)):
if char == term[i]:
count = count + 1
else:
if char != '':
result = result + char + '^' + str(count)
count = 1
char = term[i]
if char != '':
result = result + char + '^' + str(count)
return result
def unbox(self, term):
result = ''
for t in range(0,len(term),3):
variable = term[t]
power = int(term[t+2])
for p in range(0,power):
result = result + variable
return result
e = Equation(['a^1', 'b^1', 'c^1'], [1, 2, 3]) #(a + 2b + 3c)
r = Equation([''], [1]) # identity
for i in range(0,6):
r = r.multiply(e)
print r
print r.coeff("a^1b^2c^3")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment