DesignLab 1: I'm hoping to help everyone that gets stuck on the labs by sharing the code that I have written. It is not the only way to solve a problem, and sorry for the lack of comments!! Hopefully you can follow along :)
def fib(n): if n == 0: return 1 else: return n * fib(n-1)
class V2(object): def __init__(self,x,y): self.x = x self.y = y def __str__(self): return "V2 - (%s, %s)" %(self.x,self.y) def getX(self): return self.x def getY(self): return self.y def add(self,b): x = self.x + b.getX() y = self.y + b.getY() return V2(x,y) def __add__(self,b): return self.add(b) def mul(self, s): x = self.x * s y = self.y * s return V2(x,y) def __mul__(self,s): return self.mul(s)
class Polynomial: def __init__(self,l): self.coef = l def __str__(self): output = "" count = len(self.coef) for coef in self.coef: if count > 2: output = output + str(coef) + "z**" + str(count-1) + " + " elif count > 1: output = output + str(coef) + "z" + " + " else: output = output + str(coef) count -= 1 return output def add(self,b): l = [] i = 0 if len(self.coef) > len(b.coef): diff = len(self.coef)-len(b.coef) while i < len(self.coef): if i >= diff: l.append(self.coef[i]+b.coef[i-diff]) i += 1 else: l.append(self.coef[i]) i += 1 else: diff = len(b.coef)-len(self.coef) while i < len(b.coef): if i >= diff: l.append(self.coef[i-diff]+b.coef[i]) i += 1 else: l.append(b.coef[i]) i += 1 return Polynomial(l) def __add__(self,b): return self.add(b) def val(self,value): output = 0.0 count = len(self.coef) - 1 for coef in self.coef: output = output + coef * (value ** count) count -= 1 return output def __call__(self,value): return self.val(value) def mul(self, b): assert len(b.coef) == len(self.coef) l = [] len_a = len(self.coef) for i in range(len_a): for j in range(len_a): place = i + j if place < (len(l)) and i > 0: # print "if : i %s j %s" % (i,j) # print "place : ", place l[place] = l[place] + (self.coef[i]*b.coef[j]) # print "l : ", l else: # print "else : i %s j %s" % (i,j) l.append(self.coef[i]*b.coef[j]) return Polynomial(l) def __mul__(self,s): return self.mul(s) def roots(self): roots = [] if len(self.coef) == 1: roots.append(self.coef) return roots elif len(self.coef) == 2: roots.append((self.coef[1]*(-1.0))/self.coef[0]) return roots elif len(self.coef) == 3: a = self.coef[0] b = self.coef[1] c = self.coef[2] disc = b**2 - 4 * a * c # Find Complex Root if disc < 0: real = (-1.0 * b) / (2 * a) imaginary = ((-1.0*disc) ** (0.5)) / (2 * a) roots.append( complex(real,imaginary) ) roots.append( complex(real,(-1.0 * imaginary)) ) return roots # Find Normal Root else: roots.append( ((-1.0*b) + ( disc ** (0.5) ))/( 2 * a) ) roots.append( ((-1.0*b) - ( disc ** (0.5) ))/( 2 * a) ) return roots elif len(self.coef) > 3: return "Order to high"
Join our real-time social learning platform and learn together with your friends!