Habluka's Weekly Challenge #1
#21
binomial expander in Python
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:
>>> 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.
Thanks given by:


Messages In This Thread
Habluka's Weekly Challenge #1 - by Habluka - 21 May 12, 08:24AM
RE: Habluka's Weekly Challenge #1 - by Flames - 21 May 12, 08:45AM
RE: Habluka's Weekly Challenge #1 - by Habluka - 21 May 12, 09:36AM
RE: Habluka's Weekly Challenge #1 - by Sepehr - 21 May 12, 10:00AM
RE: Habluka's Weekly Challenge #1 - by Marti - 21 May 12, 02:04PM
RE: Habluka's Weekly Challenge #1 - by Habluka - 21 May 12, 10:16PM
RE: Habluka's Weekly Challenge #1 - by Jason - 21 May 12, 11:25AM
RE: Habluka's Weekly Challenge #1 - by Sepehr - 21 May 12, 11:28AM
RE: Habluka's Weekly Challenge #1 - by tempest - 21 May 12, 02:12PM
RE: Habluka's Weekly Challenge #1 - by Sepehr - 21 May 12, 02:26PM
RE: Habluka's Weekly Challenge #1 - by Sepehr - 23 May 12, 09:47AM
RE: Habluka's Weekly Challenge #1 - by RCJD - 24 May 12, 04:49AM
RE: Habluka's Weekly Challenge #1 - by Flames - 24 May 12, 05:31AM
RE: Habluka's Weekly Challenge #1 - by Sepehr - 24 May 12, 07:58AM
RE: Habluka's Weekly Challenge #1 - by Bullpup - 24 May 12, 07:16PM
RE: Habluka's Weekly Challenge #1 - by Lantry - 24 May 12, 09:27PM
RE: Habluka's Weekly Challenge #1 - by Habluka - 24 May 12, 10:47PM
RE: Habluka's Weekly Challenge #1 - by Habluka - 27 May 12, 06:44AM