Evaluate binomial coefficients: Difference between revisions
Content deleted Content added
→Functional: Removed obfuscated Python solution. |
|||
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(enumFromTo(1)(x)) |
|||
# product :: [Num] -> Num |
|||
def product(xs): |
|||
return reduce(lambda a, b: a * b, xs, 1) |
|||
# TESTS --------------------------------------------------- |
|||
print( |
|||
binomialCoefficient(5)(3) |
|||
) |
|||
# k=0 to k=5, where n=5 |
|||
print( |
|||
list(map( |
|||
binomialCoefficient(5), |
|||
enumFromTo(0)(5) |
|||
)) |
|||
)</lang> |
|||
{{Out}} |
|||
<pre>10 |
|||
[1, 5, 10, 10, 5, 1]</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |