- The Python Apprentice
- Robert Smallshire Austin Bingham
- 176字
- 2021-07-02 22:16:53
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
推薦閱讀
- Reporting with Visual Studio and Crystal Reports
- 動手玩轉Scratch3.0編程:人工智能科創教育指南
- HTML5 移動Web開發從入門到精通(微課精編版)
- 游戲程序設計教程
- PhpStorm Cookbook
- Nexus規模化Scrum框架
- Drupal 8 Module Development
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- 詳解MATLAB圖形繪制技術
- HTML5開發精要與實例詳解
- jQuery Mobile Web Development Essentials(Second Edition)
- MongoDB Administrator’s Guide
- 深入大型數據集:并行與分布化Python代碼
- Python高性能編程(第2版)
- Getting Started with RethinkDB