[Tutor] converting unkown amount of input into strings
Julieta Rangel
julieta_rangel@hotmail.com
Tue, 01 May 2001 22:17:19 -0500
I have a dumb question. I'm trying to write a program which differentiates
polynomials. In this program, the user enters the degree of the polynomial,
and then is asked for the coefficients of the polynomial. How can I store
these coefficients into a list or into a string so that I can use them later
in the following line:
r = Poly (c=[])
This is what I have so far:
import string
class Poly:
def __init__ ( self, v = 'x', c = [0]):
"""__init__():
Initializes a polynomial
Default variable is x
Default polynomial is zero"""
self.var = v
self.coef = c
self.deg = len(c)-1
def __str__ (self):
"""__str__():
Converts a polynomial into a string"""
x = `self.coef[0]`
for i in range (1, self.deg+1):
x = x + " + " + `self.coef[i]` + self.var + "^" + `i`
return x
def Derivative(p):
"""Input: an instance of a polynomial
Output: a polynomial that is the derivative of the input polynomial
Side Effects: None"""
pv=p.var
pc=[]
if p.deg==0:
return Poly (v=pv,c=[0])
else:
for i in range(0,p.deg):
d=(i+1)*p.coef[i+1]
pc.append(d)
return Poly (v=pv,c=pc)
I want the input (the coefficients)from the following line to be stored on a
string, or list so that I can use them later on (keep scrolling until you
find the place where I want to insert the coefficients entered)
a = input ("Enter the degree of your polynomial ")
i = 1
while i<=a+1:
b=a
while b>=0:
w = input("Enter coefficient of x^ %s." % (b) )
b=b-1
i = i + 1
r = Poly (c=[w]) # This is where I want to insert the coefficients.
Once the person enters the coefficients, how can I
# insert them inside the brackets. The way I have it right now the program
only considers the last coefficient entered, but I want the program to
calculate the derivative of the entire input
p = Poly (c = [-1,1,2])
q = Poly (v = 'y', c = [-1,0,2,0,4,3])
m = Derivative(p)
n = Derivative(q)
o = Derivative(r)
print "The derivative of %s is: \n %s" % (p,m)
print " "
print "The derivative of %s is: \n %s" % (q,n)
print " "
print "The derivative of %s is: \n %s" % (r,o)
print " "
Again, any help will be greatly appreciated.
Julieta
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com