Skip to content

Instantly share code, notes, and snippets.

@yasyf
Created May 30, 2013 23:20
Show Gist options
  • Select an option

  • Save yasyf/5682035 to your computer and use it in GitHub Desktop.

Select an option

Save yasyf/5682035 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import math,os,sys
def clear():
os.system('cls' if os.name=='nt' else 'clear')
def init():
clear()
print "Binomial Theorem\n"
print "(aX^b+cY^d)^e"
def get_int(prompt):
print prompt
result = 0
while result == 0:
try:
result = input("> ")
except NameError:
pass
return result
def get_str(prompt):
print prompt
result = raw_input("> ")
return result
def create_variable(letter):
co = get_int("Enter Coefficient On %s" % letter.upper())
exp = get_int("Enter Exponent On %s" % letter.upper())
return (co, exp)
def nCr(n,r):
f = math.factorial
return f(n)/(f(n-r)*f(r))
def gen_term(x,y,degree,t):
t = t-1
coefficient = nCr(degree,t)
xpower = degree-t
ypower = t
xcoefficient = x[0]**xpower
xexponent = x[1]*xpower
ycoefficient = y[0]**ypower
yexponent = y[1]*ypower
total_coefficient = coefficient*xcoefficient*ycoefficient
result = ""
if total_coefficient == 0:
result = "0"
return result
elif total_coefficient > 1:
result = "(%s)" % total_coefficient
if xexponent == 1:
result = "%s(X)" % result
elif xexponent > 1:
result = "%s(X^%d)" % (result,xexponent)
if yexponent == 1:
result = "%s(Y)" % result
elif yexponent > 1:
result = "%s(Y^%d)" % (result,yexponent)
return result
def format_binomial(x,y,degree):
result = "("
if x[0] != 0 and x[1] != 0:
if x[0] != 1:
result = "%s%dX" % (result,x[0])
else:
result = "%sX" % (result)
if x[1] != 1:
result = "%s^%d" % (result,x[1])
result = "%s + " % result
if y[0] != 0 and y[1] != 0:
if y[0] != 1:
result = "%s%dY" % (result,y[0])
else:
result = "%sY" % (result)
if y[1] != 1:
result = "%s^%d" % (result,y[1])
result = "%s)" % result
if degree > 1:
result = "%s^%d" % (result,degree)
return result
def main():
init()
if len(sys.argv) == 6:
x = (int(sys.argv[1]),int(sys.argv[2]))
y = (int(sys.argv[3]),int(sys.argv[4]))
degree = int(sys.argv[5])
else:
x = create_variable("X")
y = create_variable("Y")
degree = get_int("Enter Degree")
print
print format_binomial(x,y,degree),"=",
for t in range(1,degree+2):
print gen_term(x,y,degree,t),
if t != degree+1:
print "+",
if __name__ == '__main__':
main()
@aj2134

aj2134 commented Nov 17, 2021

Copy link
Copy Markdown

Without the function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment