Run this file on the command line using the python command with the sole argument being the power of (x+y) you wish to expand.
Example:
python binomialexpansion.py 3
Will output:
x^3 + 3x^2y + 3xy^2 + y^3
| import sys | |
| power = int(eval(sys.argv[1])) | |
| strpower = str(power) | |
| coeffs = [] | |
| if power == 0: | |
| print 1 | |
| exit() | |
| if (power+1) % 2 == 0: | |
| turningp = (power+1)/2 | |
| counter = 1 | |
| else: | |
| turningp = (power+2)/2 | |
| counter = 2 | |
| for i in range(1, power+2): | |
| if i == 1: | |
| sys.stdout.write("x^"+strpower+" + ") | |
| coeffs.append(1) | |
| continue | |
| if i == power+1: | |
| print "y^"+strpower, | |
| coeffs.append(1) | |
| break | |
| if i > turningp: | |
| co = coeffs[turningp-counter] | |
| counter = counter+1 | |
| else: | |
| co = ((power-(i-2))*coeffs[i-2])/(i-1) | |
| coeffs.append(co) | |
| sys.stdout.write(str(co)) | |
| if power-(i-1) == 1: | |
| sys.stdout.write("x") | |
| else: | |
| sys.stdout.write("x^"+str(power-(i-1))) | |
| if i-1 == 1: | |
| sys.stdout.write("y ") | |
| else: | |
| sys.stdout.write("y^"+str(i-1)+" ") | |
| sys.stdout.write("+ ") |