Evaluate binomial coefficients: Difference between revisions

→‎Functional Python: pylinted for Python 3. Added {Works with} tag.
(Add min)
(→‎Functional Python: pylinted for Python 3. Added {Works with} tag.)
Line 1,916:
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>from functools import reduce
<lang python>'''Evaluation of binomial coefficients'''
 
<lang python>from functools import reduce
 
 
# binomialCoefficient :: Int -> Int -> Int
def binomialCoefficient(n):
'''n choose k, expressed in terms of
product and factorial functions.
)'''
return lambda k: product(
enumFromTo(1 + k)(n)
) // factorial(n - k)
 
 
# TEST ----------------------------------------------------
# main :: IO()
def main():
'''Tests'''
 
print(
binomialCoefficient(5)(3)
))
 
# k=0 to k=5, where n=5
print(
list(map(
binomialCoefficient(5),
enumFromTo(0)(5)
))
)</lang>
 
 
# GENERIC -------------------------------------------------
 
# enumFromTo :: (Int ->, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
 
Line 1,935 ⟶ 1,960:
# factorial :: Int -> Int
def factorial(x):
'''The factorial of x, where
x is a positive integer.
'''
return product(enumFromTo(1)(x))
 
Line 1,940 ⟶ 1,968:
# product :: [Num] -> Num
def product(xs):
'''The product of a list of
numeric values.
'''
return reduce(lambda a, b: a * b, xs, 1)
 
Line 1,945 ⟶ 1,976:
# TESTS ---------------------------------------------------
if __name__ == '__main__':
main()</lang>
 
print(
binomialCoefficient(5)(3)
)
 
# k=0 to k=5, where n=5
print(
list(map(
binomialCoefficient(5),
enumFromTo(0)(5)
))
)</lang>
{{Out}}
<pre>10
9,659

edits