Evaluate binomial coefficients: Difference between revisions
Content deleted Content added
Add min |
→Functional Python: pylinted for Python 3. Added {Works with} tag. |
||
Line 1,916: | Line 1,916: | ||
Or, abstracting a little more for legibility and ease of reuse, while currying for ease of mapping and general composition: |
Or, abstracting a little more for legibility and ease of reuse, while currying for ease of mapping and general composition: |
||
{{Works with|Python|3.7}} |
|||
⚫ | |||
<lang python>'''Evaluation of binomial coefficients''' |
|||
⚫ | |||
# binomialCoefficient :: Int -> Int -> Int |
# binomialCoefficient :: Int -> Int -> Int |
||
def binomialCoefficient(n): |
def binomialCoefficient(n): |
||
'''n choose k, expressed in terms of |
|||
product and factorial functions. |
|||
⚫ | |||
return lambda k: product( |
return lambda k: product( |
||
enumFromTo(1 + k)(n) |
enumFromTo(1 + k)(n) |
||
) // factorial(n - k) |
) // factorial(n - k) |
||
# TEST ---------------------------------------------------- |
|||
# main :: IO() |
|||
def main(): |
|||
'''Tests''' |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
)) |
|||
⚫ | |||
# GENERIC ------------------------------------------------- |
# GENERIC ------------------------------------------------- |
||
# enumFromTo :: Int |
# enumFromTo :: (Int, Int) -> [Int] |
||
def enumFromTo(m): |
def enumFromTo(m): |
||
'''Integer enumeration from m to n.''' |
|||
return lambda n: list(range(m, 1 + n)) |
return lambda n: list(range(m, 1 + n)) |
||
Line 1,935: | Line 1,960: | ||
# factorial :: Int -> Int |
# factorial :: Int -> Int |
||
def factorial(x): |
def factorial(x): |
||
'''The factorial of x, where |
|||
x is a positive integer. |
|||
''' |
|||
return product(enumFromTo(1)(x)) |
return product(enumFromTo(1)(x)) |
||
Line 1,940: | Line 1,968: | ||
# product :: [Num] -> Num |
# product :: [Num] -> Num |
||
def product(xs): |
def product(xs): |
||
'''The product of a list of |
|||
numeric values. |
|||
''' |
|||
return reduce(lambda a, b: a * b, xs, 1) |
return reduce(lambda a, b: a * b, xs, 1) |
||
Line 1,945: | Line 1,976: | ||
# TESTS --------------------------------------------------- |
# TESTS --------------------------------------------------- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</lang> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
{{Out}} |
{{Out}} |
||
<pre>10 |
<pre>10 |