or - in
{3:-4, 1:2, 0:-3}
-4x^3 + 2x - 3
# for example s = "4:3,2:1,-3:0,10:3"
def convert_str_list(s):
result = []
xs = s.split(",")
for x in xs:
ys = x.split(":")
result.append((int(ys[0]), int(ys[1])))
return result
def read_data(fname):
with open(fname) as f:
data = f.read().splitlines()
newdata = []
for line in data:
x = line.split()
newdata.append((x[0], convert_str_list(x[1]), convert_str_list(x[2])))
return newdata
read_data("poly.dat")
[('add', [(-4, 3), (2, 1), (-3, 0)], [(9, 4), (8, 3), (4, 2)]), ('mul', [(4, 3), (2, 1), (3, 2), (-3, 0)], [(9, 4), (8, 3), (4, 2)])]
def add(p1,p2):
pass
def mul(p1,p2):
pass
def convert_list_file_str(p):
result = ""
for t in p:
result = result + str(t[0]) + ":" + str(t[1]) + ","
return result[:-1]
convert_list_file_str([(-4, 3), (2, 1), (-3, 0)])
'-4:3,2:1,-3:0'
def convert_list_display_str(p): remove all terms with 0 coefficient sort p in descending order of exponent for t in p: exponent = 0 exponent = 1 first term should not have a + sign in front of it positive coeff vs negative coeff
Monday 11 m to 2pm Thursday 9 am to Noon or email me the time
multiply polynomials
result = {}
#Nested for loop
for t1 in p1:
for t2 in p2:
multiply t1 and t2 to get a new term
append the new term to the result using if-else
convert result into a list and then return the list
add polynomials
result = {}
# sequence of two for-loops
for t1 in p1:
append t1 to result using if-else
for t2 in p2:
append t2 to result using if-else
convert result into a list and then return the list
def main():
data = read_data(sys.argv[1])
for x in data:
if x[0] == "add":
???
else:
???