# Print the polynomial (x + 1)^n
# Matt Bishop, February 27, 2012
# ECS 10, Winter Quarter 2012
# 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 = int(input("n (EOF to quit): "))
except EOFError: # user wants to quit, so help her
n = -1
break
except ValueError: # user didn't enter a number
print("You have to enter a non-negative n or EOF")
continue
# 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 or EOF")
# 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), 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=' ')
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()