# Test file # Matt Bishop, February 27, 2012 # ECS 10, Winter Quarter 2012 # function to print cx^p intelligently # parameter: c, the coefficient # p, the exponent # NOTE: assumes p >= 0 # side effect: prints cx^p as follows: # COEFFICIENT: if c == 1, prints "+" # if c == -1, prints "-" # if c > 0, prints "+ c" # if c < 0, prints "- c" # if c == 0, prints "" # POWER: if p == 0, prints c # if p == 1, prints x # otherwise prints x^p def prcoeff(c, p): # as described in lead comment if c == 0: pass elif p == 0: # print coefficient only print("%d" % (c), end=' ') elif p == 1 and c > 0: # don't print exponent print("+ %dx" % (c), end=' ') elif p == 1 and c < 0: # don't print exponent print("- %dx" % (c), end=' ') elif c == -1: # don't print coefficient of 1 print("- x^%d" % (p), end=' ') elif c < 0: # print it all neatly print("- %dx^%d" % (abs(c),p), end=' ') elif c == 1: # don't print coefficient of 1 print("+ x^%d" % (p)) else: # print it all neatly print("+ %dx^%d" % (c,p), end=' ') # Main routine to enable us to test fact() def main(): # get the input c = int(input("[[WARNING: numbers only!]] coefficient: ")) p = int(input("[[WARNING: numbers only!]] power (<0 quits): ")) # loop until quit while p >= 0: # say what you got so user can check print("coefficient %d, power %d, term" % (c, p)) prcoeff(c, p) print(" ") # get another input c = int(input("[[WARNING: numbers only!]] coefficient: ")) p = int(input("[[WARNING: numbers only!]] power (<0 quits): ")) # all done! say what user typed print("Quitting: c =", c, "p =", p) main()