# Print the polynomial (x + 1)^n
# ECS 10, May 11, 2009
# Matt Bishop
# function to read and vet user selection
# returns: n, the exponent in (x + 1)^n
# NOTE: n must be non-negative; return -1 to quit
def getinput():
# loop until we get good input
while True:
try:
# get the input and check the type here
n = input("n: ")
n += 0;
except EOFError: # user wants to quit, so help her
n = -1
break
# oops! let error check below do the work
# so set v to something illegal (not 0-3)
except (SyntaxError, NameError, TypeError):
n = -1
# now check the value we read/were given
if n >= 0:
break
# this is bad, so say so
print "You have to enter a non-negative n"
# it's non-negative to continue, -1 to quit
return n
# function to compute n!
# parameter: n, must be non-negative integer
# returns: n! on success
# -1 on failure (bad parameter)
def fact(n):
# check for error in call
if n < 0 or n != int(n):
return -1
# now compute n! by repeated multiplication
fact = 1
for i in range(1, n+1):
fact *= i
# return it
return fact
# 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),
elif p == 1 and c > 0:
# don't print exponent
print "+ %dx" % (c),
elif p == 1 and c < 0:
# don't print exponent
print "- %dx" % (c),
elif c == -1:
# don't print coefficient of 1
print "- x^%d" % (p),
elif c < 0:
# print it all neatly
print "- %dx^%d" % (abs(c),p),
elif c == 1:
# don't print coefficient of 1
print "+ x^%d" % (p)
else:
# print it all neatly
print "+ %dx^%d" % (c,p),
def main():
# get the input
n = getinput()
# if the input is negative, quit at once
if n >= 0:
# it's not -- for each term ...
for i in range(n+1):
# generate the binomial coefficient and print the polynomial
prcoeff(fact(n) / (fact(i) * fact(n - i)), i)
main()