#Assignment 2 solution import math def numericInput(prompt): """Gets user input repeating until they enter a number""" accepted = False while not accepted: text = raw_input(prompt) try: #if the conversion fails, this will error before it returns return float(text) except: print "Please enter a number" def equationText(coefs): """Returns a string containing the equation written out For example, equationText([1,0,1]) returns "1*x^2 + 0*x + 1" """ output = "" output = str(coefs[0]) + "*x^2 " if coefs[1] < 0: output += "- " else: output += "+ " output += str(abs(coefs[1])) + "*x " if coefs[2] < 0: output += "- " else: output += "+ " output += str(abs(coefs[2])) return output def evaluateEquation(coefs, x): """Evaluates the equation defined by coefs and returns the value at x""" ans = coefs[0] * x**2 ans += coefs[1] * x ans += coefs[2] return ans def readEquation(): """Reads in the coefficients for an equation""" print "A*x^2 + B*x + C" coefs=[0,0,0] coefs[0] = numericInput("A=") coefs[1] = numericInput("B=") coefs[2] = numericInput("C=") return coefs def printGraphRow(coefs1,coefs2,y): """returns the row of the graph for the given value of y""" output = str(y) + "\t" for i in range(41): x = -10 + .5*i mark1 = abs(evaluateEquation(coefs1,x)-y) < .5 mark2 = abs(evaluateEquation(coefs2,x)-y) < .5 if mark1 and mark2: output+="@" elif mark1: output+="1" elif mark2: output+="2" else: if x == 0: output+="|" elif y == 0: output+="-" else: output += " " print output def printGraph(coefs1,coefs2): """prints the graph of the 2 equations given as input""" print y = 10 while y >= -10: printGraphRow(coefs1,coefs2,y) y = y - 1 print "\t -8 -6 -4 -2 0 2 4 6 8" return option = 0 print "Enter Equation-1 Coefficients" firstEqCoefs = readEquation() print "\nEnter Equation-2 Coefficients" secondEqCoefs = readEquation() #repeat until user decides to exit while option != 5: print "\nEquation-1: " + equationText(firstEqCoefs) print "Equation-2: " + equationText(secondEqCoefs) print "\n1. Re-enter Equation-1 Coefficients" print "2. Re-enter Equation-2 Coefficients" print "3. Evaluate equations for given x" print "4. Print Graph of the equations" print "5. Exit" print "----------------------------------" option = numericInput("Select an option: ") if option == 1: print "\nEnter Equation-1 Coefficients" firstEqCoefs = readEquation() elif option == 2: print "\nEnter Equation-2 Coefficients" secondEqCoefs = readEquation() elif option == 3: print x = numericInput("Enter a value for x: ") print "Equation-1 evaluates to",evaluateEquation(firstEqCoefs,x) print "Equation-2 evaluates to",evaluateEquation(secondEqCoefs,x) elif option == 4: printGraph(firstEqCoefs,secondEqCoefs) elif option == 5: print "Exiting" else: print "Please make a valid selection."