Counting fruit with math.factorial()

Let's use factorials to compute how many ways there are to draw three fruit from a set of five fruit using some math we learned in school:

>>> n = 5
>>> k = 3
>>> math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
10.0

This simple expression is quite verbose with all those references to the math module. The Python import statement has an alternative form that allows us to bring a specific function from a module into the current namespace by using the from keyword:

>>> from math import factorial
>>> factorial(n) / (factorial(k) * factorial(n - k))
10.0

This is a good improvement, but is still a little long-winded for such a simple expression.

A third form of the import statement allows us to rename the imported function. This can be useful for reasons of readability, or to avoid a namespace clash. Useful as it is, though, we recommend that this feature be used infrequently and judiciously:

>>> from math import factorial as fac
>>> fac(n) / (fac(k) * fac(n - k))
10.0


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset