Evaluate binomial coefficients: Difference between revisions
Content added Content deleted
(→Functional Applescript: Added a reduced variant of the main function) |
(→{{header|Python}}: Added a second (Python 3 compatible) functional version) |
||
Line 1,865: | Line 1,865: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Imperative=== |
|||
Straight-forward implementation: |
|||
<lang python>def binomialCoeff(n, k): |
<lang python>def binomialCoeff(n, k): |
||
result = 1 |
result = 1 |
||
Line 1,877: | Line 1,877: | ||
<pre>10</pre> |
<pre>10</pre> |
||
===Functional=== |
|||
'''Alternate implementation''' |
|||
<lang python>from operator import mul |
<lang python>from operator import mul |
||
def comb(n,r): |
def comb(n,r): |
||
Line 1,895: | Line 1,895: | ||
return int( reduce( mul, range((n-r+1), n+1), 1) / |
return int( reduce( mul, range((n-r+1), n+1), 1) / |
||
reduce( mul, range(1,r+1), 1) )</lang> |
reduce( mul, range(1,r+1), 1) )</lang> |
||
Or, updating for Python 3, and abstracting a little more for legibility and ease of reuse, while currying for ease of mapping and general composition: |
|||
<lang python>from functools import reduce |
|||
# binomialCoefficient :: Int -> Int -> Int |
|||
def binomialCoefficient(n): |
|||
return lambda k: product( |
|||
enumFromTo(1 + k)(n) |
|||
) // factorial(n - k) |
|||
# GENERIC ------------------------------------------------- |
|||
# enumFromTo :: Int -> Int -> [Int] |
|||
def enumFromTo(m): |
|||
return lambda n: range(m, 1 + n) |
|||
# factorial :: Int -> Int |
|||
def factorial(x): |
|||
return product(range(1, 1 + x)) |
|||
# product :: [Num] -> Num |
|||
def product(xs): |
|||
return reduce(lambda a, b: a * b, xs, 1) |
|||
# TEST ------------------------------------------------- |
|||
print( |
|||
binomialCoefficient(5)(3) |
|||
)</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |