Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Code in 2.7, thanks! A polynomial p(t) of degree n is defined as: p(t) =

ID: 3603392 • Letter: P

Question

Python Code in 2.7, thanks!

A polynomial p(t) of degree n is defined as: p(t) = antn + an-t"- + + alt + a0 Forn 0,1,... , 5, fit a polynomial of degree n by least squares to the following data: t 0.0 1.0 2.0 3.0 4.0 5.0 p(t) 1.0 2.7 5.8 6.6 7.5 9.9 Make a plot of the original data points along with each resulting polynomial curve (you may make separate graphs for each curve, or a single graph containing all of the curves). Which polynomial would you say captures the general trend of the data better'?

Explanation / Answer


def enumerate2(xs, start=0, step=1):
for x in xs:
yield (start, x)
start += step

def poly(xs):
"""Return string representation of a polynomial.

>>> poly([2,1,0])
"2x^2 + x"
"""
res = []
for e, x in enumerate2(xs, len(xs)-1, -1):

variable = 'x'

if x == 1:
coefficient = ''
elif x == -1:
coefficient = '-'
else:
coefficient = str(x)

if e == 1:
power = ''
elif e == 0:
power = ''
variable = ''
else:
power = '^' + str(e)

if x < 0:
coefficient = '(' + coefficient
power = power + ')'

if x != 0:
res.append(coefficient + variable + power)

return ' + '.join(res)
import collections
import itertools

class Polynomial(object):
def __init__(self, *args):
"""
Create a polynomial in one of three ways:

p = Polynomial(poly) # copy constructor
p = Polynomial([1,2,3 ...]) # from sequence
p = Polynomial(1, 2, 3 ...) # from scalars
"""
super(Polynomial,self).__init__()
if len(args)==1:
val = args[0]
if isinstance(val, Polynomial): # copy constructor
self.coeffs = val.coeffs[:]
elif isinstance(val, collections.Iterable): # from sequence
self.coeffs = list(val)
else: # from single scalar
self.coeffs = [val+0]
else: # multiple scalars
self.coeffs = [i+0 for i in args]
self.trim()

def __add__(self, val):
"Return self+val"
if isinstance(val, Polynomial): # add Polynomial
res = [a+b for a,b in itertools.izip_longest(self.coeffs, val.coeffs, fillvalue=0)]
else: # add scalar
if self.coeffs:
res = self.coeffs[:]
res[0] += val
else:
res = val
return self.__class__(res)

def __call__(self, val):
"Evaluate at X==val"
res = 0
pwr = 1
for co in self.coeffs:
res += co*pwr
pwr *= val
return res

def __eq__(self, val):
"Test self==val"
if isinstance(val, Polynomial):
return self.coeffs == val.coeffs
else:
return len(self.coeffs)==1 and self.coeffs[0]==val

def __mul__(self, val):
"Return self*val"
if isinstance(val, Polynomial):
_s = self.coeffs
_v = val.coeffs
res = [0]*(len(_s)+len(_v)-1)
for selfpow,selfco in enumerate(_s):
for valpow,valco in enumerate(_v):
res[selfpow+valpow] += selfco*valco
else:
res = [co*val for co in self.coeffs]
return self.__class__(res)

def __neg__(self):
"Return -self"
return self.__class__([-co for co in self.coeffs])

def __pow__(self, y, z=None):
raise NotImplemented()

def _radd__(self, val):
"Return val+self"
return self+val

def __repr__(self):
return "{0}({1})".format(self.__class__.__name__, self.coeffs)

def __rmul__(self, val):
"Return val*self"
return self*val

def __rsub__(self, val):
"Return val-self"
return -self + val

def __str__(self):
"Return string formatted as aX^3 + bX^2 + c^X + d"
res = []
for po,co in enumerate(self.coeffs):
if co:
if po==0:
po = ''
elif po==1:
po = 'X'
else:
po = 'X^'+str(po)
res.append(str(co)+po)
if res:
res.reverse()
return ' + '.join(res)
else:
return "0"

def __sub__(self, val):
"Return self-val"
return self.__add__(-val)

def trim(self):
"Remove trailing 0-coefficients"
_co = self.coeffs
if _co:
offs = len(_co)-1
if _co[offs]==0:
offs -= 1
while offs >= 0 and _co[offs]==0:
offs -= 1
del _co[offs+1:]

import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
a=int(input("Enter coefficient:"))
lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
while(j>0):
sum1=sum1+(lst[i]*math.pow(x,j))
break
j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)


def addpoly(p1,p2):
for i in range(len(p1)):
for item in p2:
if p1[i][1] == item[1]:
p1[i] = ((p1[i][0] + item[0]),p1[i][1])
p2.remove(item)
p3 = p1 + p2
for item in (p3):
if item[0] == 0:
p3.remove(item)
return sorted(p3)
def poly(lst, x):
n = len(lst)
If n==4:
return lst[o]+lst[1]*x+lst[2]*x**2+lst[3]*x**3
elif n==3:
return lst[o]+lst[1]*x+lst[2]*x**2
elif n==2:
return lst[o]+lst[1]*x
elif n==1:
return lst[o]
else:
return lst[o]+lst[1]*x+lst[2]*x**2+lst[3]*x**3+lst[n]*x**n
def multpoly(p1,p2):

dp1=dict(map(reversed, p1))
dp2=dict(map(reversed, p2))
kdp1=list(dp1.keys())
kdp2=list(dp2.keys())

rslt={}
if len(kdp1)>=len(kdp2):
kd1=kdp1
kd2=kdp2
elif len(kdp1)<len(kdp2):
kd1=kdp2
kd2=kdp1
for n in kd2:
for m in kd1:
rslt[n]={m:0}
if len(dp1)<=len(dp2):
rslt[n][m+n]=rslt[n][m+n] + dp1[n]*dp2[m]
elif len(dp1)>len(dp2):
rslt[n][m+n]=rslt[n][m+n] + dp2[n]*dp1[m]
return(rslt)
def multiply_terms(term_1, term_2):
new_c = term_1[0] * term_2[0]
new_e = term_1[1] + term_2[1]
return (new_c, new_e)


def multpoly(p1, p2):
"""
@params p1,p2 are lists of tuples where each tuple represents a pair of term coefficient and exponent
"""
# multiply terms
result_poly = []
for term_1 in p1:
for term_2 in p2:
result_poly.append(multiply_terms(term_1, term_2))
# collect like terms
collected_terms = []
exps = [term[1] for term in result_poly]
for e in exps:
count = 0
for term in result_poly:
if term[1] == e:
count += term[0]
collected_terms.append((count, e))
return collected_terms