官术网_书友最值得收藏!

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


主站蜘蛛池模板: 云龙县| 原平市| 汉源县| 定远县| 商南县| 万源市| 马关县| 阳高县| 宁陵县| 新乐市| 沽源县| 稷山县| 吐鲁番市| 高碑店市| 卢龙县| 克拉玛依市| 武隆县| 清镇市| 大理市| 萨嘎县| 长治市| 休宁县| 上虞市| 山阴县| 东乌| 昌平区| 修文县| 遂川县| 喀什市| 余江县| 孟连| 马山县| 准格尔旗| 昌吉市| 上饶市| 延边| 同仁县| 泰宁县| 靖西县| 石景山区| 海门市|