Evaluate binomial coefficients: Difference between revisions

Content added Content deleted
(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>from functools import reduce
<lang python>'''Evaluation of binomial coefficients'''

from functools import reduce




# 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'''

print(
binomialCoefficient(5)(3)
)

# k=0 to k=5, where n=5
print(
list(map(
binomialCoefficient(5),
enumFromTo(0)(5)
))
)




# GENERIC -------------------------------------------------
# GENERIC -------------------------------------------------


# enumFromTo :: Int -> Int -> [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>

print(
binomialCoefficient(5)(3)
)

# k=0 to k=5, where n=5
print(
list(map(
binomialCoefficient(5),
enumFromTo(0)(5)
))
)</lang>
{{Out}}
{{Out}}
<pre>10
<pre>10