binomial expander in Python
example use:
the ' + 0' at the end is simply lazy coding on my part, I might clean the whole thing up in a bit, but for now you get the 'technically correct' version.
[SELECT ALL] Code:
def expand(s):
""" Input: string representation of a binomial in the form (a+b)^n
Output: string representation of the expanded form
"""
n = s[s.rfind('^')+1:]
a = s[s.find('(')+1:s.find('+')]
b = s[s.find('+')+1:s.find(')')]
result = ''
row = pascal_row(int(n))
for i in range(int(n)+1):
result += str(row[i]) \
+ '(' + a + '^' + str(int(n) - i) + ')' \
+ '(' + b + '^' + str(i) + ') + '
return result + '0'
def pascal_row(row_num):
"""
http://mail.python.org/pipermail/edu-sig/2010-January/009758.html
"""
numer = row_num
denom = 1
# initialize row of Pascal's Triangle
row = [1]
while numer > 0:
row.append((row[-1] * numer/denom))
numer -= 1 # decrement numerator
denom += 1 # increment denominator
return row
example use:
[SELECT ALL] Code:
>>> expand('(x+y)^2')
'1(x^2)(y^0) + 2(x^1)(y^1) + 1(x^0)(y^2) + 0'
the ' + 0' at the end is simply lazy coding on my part, I might clean the whole thing up in a bit, but for now you get the 'technically correct' version.