diff --git a/docs/da/002.md b/docs/da/002.md index 5ebc9907a..a9657749b 100644 --- a/docs/da/002.md +++ b/docs/da/002.md @@ -14,7 +14,7 @@ 安装好 `Python` 之后,在命令行下输入: -``` +```py python ``` @@ -24,12 +24,12 @@ python In [1]: -``` +```py print "hello world!" ``` -``` +```py hello world! ``` @@ -38,7 +38,7 @@ hello world! 可以将这句话的内容保存到一个文本文件中,并使用后缀名 `.py` 结尾,例如 `hello_world.py`,在命令行下运行这个程序: -``` +```py python hello_world.py ``` @@ -54,12 +54,12 @@ python hello_world.py In [2]: -``` +```py import this ``` -``` +```py The Zen of Python, by Tim Peters Beautiful is better than ugly. @@ -88,7 +88,7 @@ Namespaces are one honking great idea -- let's do more of those! In [3]: -``` +```py s = """Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. @@ -120,7 +120,7 @@ print "".join([d.get(c, c) for c in s]) ``` -``` +```py The Zen of Python, by Tim Peters Beautiful is better than ugly. diff --git a/docs/da/003.md b/docs/da/003.md index b44ed7a3c..586c353a7 100644 --- a/docs/da/003.md +++ b/docs/da/003.md @@ -4,7 +4,7 @@ 通常我们并不使用**Python**自带的解释器,而是使用另一个比较方便的解释器——**ipython**解释器,命令行下输入: -``` +```py ipython ``` @@ -14,12 +14,12 @@ ipython In [1]: -``` +```py print "hello, world" ``` -``` +```py hello, world ``` @@ -28,7 +28,7 @@ hello, world In [2]: -``` +```py a = 1 ``` @@ -37,20 +37,20 @@ a = 1 In [3]: -``` +```py a ``` Out[3]: -``` +```py 1 ``` In [4]: -``` +```py b = [1, 2, 3] ``` @@ -63,14 +63,14 @@ b = [1, 2, 3] In [5]: -``` +```py %lsmagic ``` Out[5]: -``` +```py Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %config %connect_info %copy %ddir %debug %dhist %dirs %doctest_mode %echo %ed %edit %env %gui %hist %history %install_default_config %install_ext %install_profiles %killbgscripts %ldir %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %macro %magic %matplotlib %mkdir %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %ren %rep %rerun %reset %reset_selective %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode @@ -90,12 +90,12 @@ Automagic is ON, % prefix IS NOT needed for line magics. In [6]: -``` +```py %whos ``` -``` +```py Variable Type Data/Info ---------------------------- a int 1 @@ -107,7 +107,7 @@ b list n=3 In [7]: -``` +```py %reset -f ``` @@ -116,12 +116,12 @@ In [7]: In [8]: -``` +```py %whos ``` -``` +```py Interactive namespace is empty. ``` @@ -130,14 +130,14 @@ Interactive namespace is empty. In [9]: -``` +```py %pwd ``` Out[9]: -``` +```py u'C:\\Users\\lijin\\Documents\\Git\\python-tutorial\\01\. python tools' ``` @@ -145,7 +145,7 @@ u'C:\\Users\\lijin\\Documents\\Git\\python-tutorial\\01\. python tools' In [10]: -``` +```py %mkdir demo_test ``` @@ -154,12 +154,12 @@ In [10]: In [11]: -``` +```py %cd demo_test/ ``` -``` +```py C:\Users\lijin\Documents\Git\python-tutorial\01\. python tools\demo_test ``` @@ -168,13 +168,13 @@ C:\Users\lijin\Documents\Git\python-tutorial\01\. python tools\demo_test In [12]: -``` +```py %%writefile hello_world.py print "hello world" ``` -``` +```py Writing hello_world.py ``` @@ -183,12 +183,12 @@ Writing hello_world.py In [13]: -``` +```py %ls ``` -``` +```py 驱动器 C 中的卷是 System 卷的序列号是 DC4B-D785 @@ -206,12 +206,12 @@ In [13]: In [14]: -``` +```py %run hello_world.py ``` -``` +```py hello world ``` @@ -220,7 +220,7 @@ hello world In [15]: -``` +```py import os os.remove('hello_world.py') @@ -230,12 +230,12 @@ os.remove('hello_world.py') In [16]: -``` +```py %ls ``` -``` +```py 驱动器 C 中的卷是 System 卷的序列号是 DC4B-D785 @@ -252,12 +252,12 @@ In [16]: In [17]: -``` +```py %cd .. ``` -``` +```py C:\Users\lijin\Documents\Git\python-tutorial\01\. python tools ``` @@ -266,7 +266,7 @@ C:\Users\lijin\Documents\Git\python-tutorial\01\. python tools In [18]: -``` +```py %rmdir demo_test ``` @@ -275,12 +275,12 @@ In [18]: In [19]: -``` +```py %hist ``` -``` +```py print "hello, world" a = 1 a @@ -311,7 +311,7 @@ os.remove('hello_world.py') In [20]: -``` +```py sum? ``` @@ -320,7 +320,7 @@ sum? In [21]: -``` +```py # 导入numpy和matplotlib两个包 %pylab # 查看其中sort函数的帮助 @@ -328,7 +328,7 @@ sort?? ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -340,7 +340,7 @@ Populating the interactive namespace from numpy and matplotlib In [22]: -``` +```py a = 12 a @@ -348,20 +348,20 @@ a Out[22]: -``` +```py 12 ``` In [23]: -``` +```py _ + 13 ``` Out[23]: -``` +```py 25 ``` @@ -369,12 +369,12 @@ Out[23]: In [24]: -``` +```py !ping baidu.com ``` -``` +```py 正在 Ping baidu.com [180.149.132.47] 具有 32 字节的数据: 来自 180.149.132.47 的回复: 字节=32 时间=69ms TTL=49 来自 180.149.132.47 的回复: 字节=32 时间=64ms TTL=49 @@ -392,12 +392,12 @@ In [24]: In [25]: -``` +```py 1 + "hello" ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () diff --git a/docs/da/004.md b/docs/da/004.md index df0f6c0c3..bc372ed57 100644 --- a/docs/da/004.md +++ b/docs/da/004.md @@ -2,7 +2,7 @@ 在命令行下输入命令: -``` +```py ipython notebook ``` diff --git a/docs/da/005.md b/docs/da/005.md index ca7ab8d13..defb99c3b 100644 --- a/docs/da/005.md +++ b/docs/da/005.md @@ -6,7 +6,7 @@ 根据自己的操作系统安装好[Anaconda](http://www.continuum.io/downloads)后,在命令行下输入: -``` +```py conda list ``` @@ -14,12 +14,12 @@ conda list In [1]: -``` +```py !conda list ``` -``` +```py # packages in environment at C:\Anaconda: # _license 1.1 py27_0 @@ -169,7 +169,7 @@ zlib 1.2.8 0 第一次安装好 [Anaconda](http://www.continuum.io/downloads) 以后,可以在命令行输入以下命令使 [Anaconda](http://www.continuum.io/downloads) 保持最新: -``` +```py conda update conda conda update anaconda ``` @@ -180,7 +180,7 @@ conda 是一种很强大的工具,具体用法可以参照它的[文档](http: 可以使用它来安装,更新,卸载第三方的 **python** 工具包: -``` +```py conda install conda update conda remove @@ -188,25 +188,25 @@ conda remove 在安装或更新时可以指定安装的版本号,例如需要使用 `numpy 1.8.1`: -``` +```py conda install numpy=1.8.1 conda update numpy=1.8.1 ``` 查看 `conda` 的信息: -``` +```py conda info ``` In [2]: -``` +```py !conda info ``` -``` +```py Current conda install: platform : win-64 @@ -229,7 +229,7 @@ Current conda install: 一个很棒的功能是 `conda` 可以产生一个自定义的环境,假设在安装的是 **Python 2.7** 的情况下,想使用 **Python 3.4**,只需要在命令行下使用 `conda` 产生一个新的环境: -``` +```py conda create -n py34 python=3.4 ``` @@ -237,7 +237,7 @@ conda create -n py34 python=3.4 使用这个环境时,只需要命令行下输入: -``` +```py activate py34 #(windows) source activate py34 #(linux, mac) @@ -249,7 +249,7 @@ source activate py34 #(linux, mac) `Anaconda` 默认使用的编辑器是 `spyder`,可以在命令行下输入: -``` +```py spyder ``` diff --git a/docs/da/007.md b/docs/da/007.md index fac06cc1c..53a48fd1e 100644 --- a/docs/da/007.md +++ b/docs/da/007.md @@ -6,14 +6,14 @@ In [1]: -``` +```py 2 + 2 ``` Out[1]: -``` +```py 4 ``` @@ -21,14 +21,14 @@ Out[1]: In [2]: -``` +```py 2.0 + 2.5 ``` Out[2]: -``` +```py 4.5 ``` @@ -36,14 +36,14 @@ Out[2]: In [3]: -``` +```py 2 + 2.5 ``` Out[3]: -``` +```py 4.5 ``` @@ -53,7 +53,7 @@ Out[3]: In [4]: -``` +```py a = 0.2 ``` @@ -64,7 +64,7 @@ a = 0.2 In [5]: -``` +```py s = "hello world" s @@ -72,13 +72,13 @@ s Out[5]: -``` +```py 'hello world' ``` In [6]: -``` +```py s = 'hello world' s @@ -86,7 +86,7 @@ s Out[6]: -``` +```py 'hello world' ``` @@ -94,14 +94,14 @@ Out[6]: In [7]: -``` +```py s = """hello world""" print s ``` -``` +```py hello world @@ -109,14 +109,14 @@ world In [8]: -``` +```py s = '''hello world''' print s ``` -``` +```py hello world @@ -126,7 +126,7 @@ world In [9]: -``` +```py s = "hello" + " world" s @@ -134,7 +134,7 @@ s Out[9]: -``` +```py 'hello world' ``` @@ -142,40 +142,40 @@ Out[9]: In [10]: -``` +```py s[0] ``` Out[10]: -``` +```py 'h' ``` In [11]: -``` +```py s[-1] ``` Out[11]: -``` +```py 'd' ``` In [12]: -``` +```py s[0:5] ``` Out[12]: -``` +```py 'hello' ``` @@ -183,7 +183,7 @@ Out[12]: In [13]: -``` +```py s = "hello world" s.split() @@ -191,7 +191,7 @@ s.split() Out[13]: -``` +```py ['hello', 'world'] ``` @@ -199,14 +199,14 @@ Out[13]: In [14]: -``` +```py len(s) ``` Out[14]: -``` +```py 11 ``` @@ -216,7 +216,7 @@ Python用`[]`来生成列表 In [15]: -``` +```py a = [1, 2.0, 'hello', 5 + 1.0] a @@ -224,7 +224,7 @@ a Out[15]: -``` +```py [1, 2.0, 'hello', 6.0] ``` @@ -232,14 +232,14 @@ Out[15]: In [16]: -``` +```py a + a ``` Out[16]: -``` +```py [1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0] ``` @@ -247,14 +247,14 @@ Out[16]: In [17]: -``` +```py a[1] ``` Out[17]: -``` +```py 2.0 ``` @@ -262,14 +262,14 @@ Out[17]: In [18]: -``` +```py len(a) ``` Out[18]: -``` +```py 4 ``` @@ -277,7 +277,7 @@ Out[18]: In [19]: -``` +```py a.append("world") a @@ -285,7 +285,7 @@ a Out[19]: -``` +```py [1, 2.0, 'hello', 6.0, 'world'] ``` @@ -295,7 +295,7 @@ Python用{}来生成集合,集合中不含有相同元素。 In [20]: -``` +```py s = {2, 3, 4, 2} s @@ -303,7 +303,7 @@ s Out[20]: -``` +```py {2, 3, 4} ``` @@ -311,14 +311,14 @@ Out[20]: In [21]: -``` +```py len(s) ``` Out[21]: -``` +```py 3 ``` @@ -326,7 +326,7 @@ Out[21]: In [22]: -``` +```py s.add(1) s @@ -334,7 +334,7 @@ s Out[22]: -``` +```py {1, 2, 3, 4} ``` @@ -342,7 +342,7 @@ Out[22]: In [23]: -``` +```py a = {1, 2, 3, 4} b = {2, 3, 4, 5} a & b @@ -351,7 +351,7 @@ a & b Out[23]: -``` +```py {2, 3, 4} ``` @@ -359,14 +359,14 @@ Out[23]: In [24]: -``` +```py a | b ``` Out[24]: -``` +```py {1, 2, 3, 4, 5} ``` @@ -374,14 +374,14 @@ Out[24]: In [25]: -``` +```py a - b ``` Out[25]: -``` +```py {1} ``` @@ -389,14 +389,14 @@ Out[25]: In [26]: -``` +```py a ^ b ``` Out[26]: -``` +```py {1, 5} ``` @@ -406,7 +406,7 @@ Python用`{key:value}`来生成Dictionary。 In [27]: -``` +```py d = {'dogs':5, 'cats':4} d @@ -414,7 +414,7 @@ d Out[27]: -``` +```py {'cats': 4, 'dogs': 5} ``` @@ -422,14 +422,14 @@ Out[27]: In [28]: -``` +```py len(d) ``` Out[28]: -``` +```py 2 ``` @@ -437,14 +437,14 @@ Out[28]: In [29]: -``` +```py d["dogs"] ``` Out[29]: -``` +```py 5 ``` @@ -452,7 +452,7 @@ Out[29]: In [30]: -``` +```py d["dogs"] = 2 d @@ -460,7 +460,7 @@ d Out[30]: -``` +```py {'cats': 4, 'dogs': 2} ``` @@ -468,7 +468,7 @@ Out[30]: In [31]: -``` +```py d["pigs"] = 7 d @@ -476,7 +476,7 @@ d Out[31]: -``` +```py {'cats': 4, 'dogs': 2, 'pigs': 7} ``` @@ -484,14 +484,14 @@ Out[31]: In [32]: -``` +```py d.keys() ``` Out[32]: -``` +```py ['cats', 'dogs', 'pigs'] ``` @@ -499,14 +499,14 @@ Out[32]: In [33]: -``` +```py d.values() ``` Out[33]: -``` +```py [4, 2, 7] ``` @@ -514,14 +514,14 @@ Out[33]: In [34]: -``` +```py d.items() ``` Out[34]: -``` +```py [('cats', 4), ('dogs', 2), ('pigs', 7)] ``` @@ -531,7 +531,7 @@ Out[34]: In [35]: -``` +```py from numpy import array a = array([1, 2, 3, 4]) a @@ -540,7 +540,7 @@ a Out[35]: -``` +```py array([1, 2, 3, 4]) ``` @@ -548,27 +548,27 @@ array([1, 2, 3, 4]) In [36]: -``` +```py a + 2 ``` Out[36]: -``` +```py array([3, 4, 5, 6]) ``` In [37]: -``` +```py a + a ``` Out[37]: -``` +```py array([2, 4, 6, 8]) ``` @@ -578,7 +578,7 @@ Python提供了一个很像MATLAB的绘图接口。 In [38]: -``` +```py %matplotlib inline from matplotlib.pyplot import plot plot(a, a**2) @@ -587,7 +587,7 @@ plot(a, a**2) Out[38]: -``` +```py [] ``` @@ -685,7 +685,7 @@ SaoBg7kk1YDBXJJqwGAuSTVgMJekGvhf3kAwE/Ra4D0AAAAASUVORK5CYII= In [39]: -``` +```py line = '1 2 3 4 5' fields = line.split() fields @@ -694,13 +694,13 @@ fields Out[39]: -``` +```py ['1', '2', '3', '4', '5'] ``` In [40]: -``` +```py total = 0 for field in fields: total += int(field) @@ -710,7 +710,7 @@ total Out[40]: -``` +```py 15 ``` @@ -718,7 +718,7 @@ Python中有一种叫做列表推导式(List comprehension)的用法: In [41]: -``` +```py numbers = [int(field) for field in fields] numbers @@ -726,20 +726,20 @@ numbers Out[41]: -``` +```py [1, 2, 3, 4, 5] ``` In [42]: -``` +```py sum(numbers) ``` Out[42]: -``` +```py 15 ``` @@ -747,14 +747,14 @@ Out[42]: In [43]: -``` +```py sum([int(field) for field in line.split()]) ``` Out[43]: -``` +```py 15 ``` @@ -762,12 +762,12 @@ Out[43]: In [44]: -``` +```py cd ~ ``` -``` +```py d:\Users\lijin ``` @@ -776,7 +776,7 @@ d:\Users\lijin In [45]: -``` +```py f = open('data.txt', 'w') f.write('1 2 3 4\n') f.write('2 3 4 5\n') @@ -788,7 +788,7 @@ f.close() In [46]: -``` +```py f = open('data.txt') data = [] for line in f: @@ -800,19 +800,19 @@ data Out[46]: -``` +```py [[1, 2, 3, 4], [2, 3, 4, 5]] ``` In [47]: -``` +```py for row in data: print row ``` -``` +```py [1, 2, 3, 4] [2, 3, 4, 5] @@ -822,7 +822,7 @@ for row in data: In [48]: -``` +```py import os os.remove('data.txt') @@ -834,7 +834,7 @@ Python用关键词`def`来定义函数。 In [49]: -``` +```py def poly(x, a, b, c): y = a * x ** 2 + b * x + c return y @@ -846,7 +846,7 @@ poly(x, 1, 2, 3) Out[49]: -``` +```py 6 ``` @@ -854,7 +854,7 @@ Out[49]: In [50]: -``` +```py x = array([1, 2, 3]) poly(x, 1, 2, 3) @@ -862,7 +862,7 @@ poly(x, 1, 2, 3) Out[50]: -``` +```py array([ 6, 11, 18]) ``` @@ -870,7 +870,7 @@ array([ 6, 11, 18]) In [51]: -``` +```py from numpy import arange def poly(x, a = 1, b = 2, c = 3): @@ -885,33 +885,33 @@ array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Out[51]: -``` +```py array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` In [52]: -``` +```py poly(x) ``` Out[52]: -``` +```py array([ 3, 6, 11, 18, 27, 38, 51, 66, 83, 102]) ``` In [53]: -``` +```py poly(x, b = 1) ``` Out[53]: -``` +```py array([ 3, 5, 9, 15, 23, 33, 45, 59, 75, 93]) ``` @@ -921,7 +921,7 @@ Python中使用`import`关键词来导入模块。 In [54]: -``` +```py import os ``` @@ -930,14 +930,14 @@ import os In [55]: -``` +```py os.getpid() ``` Out[55]: -``` +```py 4400 ``` @@ -945,14 +945,14 @@ Out[55]: In [56]: -``` +```py os.sep ``` Out[56]: -``` +```py '\\' ``` @@ -962,7 +962,7 @@ Out[56]: In [57]: -``` +```py class Person(object): def __init__(self, first, last, age): self.first = first @@ -977,7 +977,7 @@ class Person(object): In [58]: -``` +```py person = Person('Mertle', 'Sedgewick', 52) ``` @@ -986,14 +986,14 @@ person = Person('Mertle', 'Sedgewick', 52) In [59]: -``` +```py person.first ``` Out[59]: -``` +```py 'Mertle' ``` @@ -1001,14 +1001,14 @@ Out[59]: In [60]: -``` +```py person.full_name() ``` Out[60]: -``` +```py 'Mertle Sedgewick' ``` @@ -1016,7 +1016,7 @@ Out[60]: In [61]: -``` +```py person.last = 'Smith' ``` @@ -1025,7 +1025,7 @@ person.last = 'Smith' In [62]: -``` +```py person.critters = d person.critters @@ -1033,7 +1033,7 @@ person.critters Out[62]: -``` +```py {'cats': 4, 'dogs': 2, 'pigs': 7} ``` @@ -1041,7 +1041,7 @@ Out[62]: In [63]: -``` +```py url = 'http://ichart.finance.yahoo.com/table.csv?s=GE&d=10&e=5&f=2013&g=d&a=0&b=2&c=1962&ignore=.csv' ``` @@ -1050,7 +1050,7 @@ url = 'http://ichart.finance.yahoo.com/table.csv?s=GE&d=10&e=5&f=2013&g=d&a=0&b= In [64]: -``` +```py import urllib2 ge_csv = urllib2.urlopen(url) data = [] @@ -1062,7 +1062,7 @@ data[:4] Out[64]: -``` +```py [['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n'], ['2013-11-05', '26.32', '26.52', '26.26', '26.42', '24897500', '24.872115\n'], ['2013-11-04', @@ -1085,7 +1085,7 @@ Out[64]: In [65]: -``` +```py ge_csv = urllib2.urlopen(url) import pandas ge = pandas.read_csv(ge_csv, index_col=0, parse_dates=True) @@ -1095,7 +1095,7 @@ ge.plot(y='Adj Close') Out[65]: -``` +```py ``` diff --git a/docs/da/009.md b/docs/da/009.md index 85c64343d..573865aa4 100644 --- a/docs/da/009.md +++ b/docs/da/009.md @@ -6,40 +6,40 @@ In [1]: -``` +```py 2 + 2 ``` Out[1]: -``` +```py 4 ``` In [2]: -``` +```py 3 - 4 ``` Out[2]: -``` +```py -1 ``` In [3]: -``` +```py 4 * 5 ``` Out[3]: -``` +```py 20 ``` @@ -49,14 +49,14 @@ Out[3]: In [4]: -``` +```py 12 / 5 ``` Out[4]: -``` +```py 2 ``` @@ -64,14 +64,14 @@ Out[4]: In [5]: -``` +```py 2 ** 5 ``` Out[5]: -``` +```py 32 ``` @@ -79,14 +79,14 @@ Out[5]: In [6]: -``` +```py 32 % 5 ``` Out[6]: -``` +```py 2 ``` @@ -94,7 +94,7 @@ Out[6]: In [7]: -``` +```py a = 1 a @@ -102,7 +102,7 @@ a Out[7]: -``` +```py 1 ``` @@ -110,14 +110,14 @@ Out[7]: In [8]: -``` +```py type(a) ``` Out[8]: -``` +```py int ``` @@ -129,7 +129,7 @@ int In [9]: -``` +```py import sys sys.maxint @@ -137,7 +137,7 @@ sys.maxint Out[9]: -``` +```py 2147483647 ``` @@ -147,13 +147,13 @@ Out[9]: In [10]: -``` +```py a = sys.maxint + 1 print type(a) ``` -``` +```py ``` @@ -162,14 +162,14 @@ print type(a) In [11]: -``` +```py a ``` Out[11]: -``` +```py 2147483648L ``` @@ -177,7 +177,7 @@ Out[11]: In [12]: -``` +```py b = 1234L type(b) @@ -185,7 +185,7 @@ type(b) Out[12]: -``` +```py long ``` @@ -193,14 +193,14 @@ long In [13]: -``` +```py a - 4 ``` Out[13]: -``` +```py 2147483644L ``` @@ -208,7 +208,7 @@ Out[13]: In [14]: -``` +```py a = 1.4 type(a) @@ -216,7 +216,7 @@ type(a) Out[14]: -``` +```py float ``` @@ -224,40 +224,40 @@ float In [15]: -``` +```py 12.0 / 5.0 ``` Out[15]: -``` +```py 2.4 ``` In [16]: -``` +```py 12 / 5.0 ``` Out[16]: -``` +```py 2.4 ``` In [17]: -``` +```py 12.0 / 5 ``` Out[17]: -``` +```py 2.4 ``` @@ -265,14 +265,14 @@ Out[17]: In [18]: -``` +```py 5 + 2.4 ``` Out[18]: -``` +```py 7.4 ``` @@ -280,53 +280,53 @@ Out[18]: In [19]: -``` +```py 3.4 - 3.2 ``` Out[19]: -``` +```py 0.19999999999999973 ``` In [20]: -``` +```py 12.3 + 32.4 ``` Out[20]: -``` +```py 44.7 ``` In [21]: -``` +```py 2.5 ** 2 ``` Out[21]: -``` +```py 6.25 ``` In [22]: -``` +```py 3.4 % 2.1 ``` Out[22]: -``` +```py 1.2999999999999998 ``` @@ -338,14 +338,14 @@ Out[22]: In [23]: -``` +```py '{:.52}'.format(3.4 - 3.2) ``` Out[23]: -``` +```py '0.199999999999999733546474089962430298328399658203125' ``` @@ -353,12 +353,12 @@ Out[23]: In [24]: -``` +```py print 3.4 - 3.2 ``` -``` +```py 0.2 ``` @@ -367,7 +367,7 @@ print 3.4 - 3.2 In [25]: -``` +```py import sys sys.float_info @@ -375,7 +375,7 @@ sys.float_info Out[25]: -``` +```py sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) ``` @@ -383,14 +383,14 @@ sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2. In [26]: -``` +```py sys.float_info.max ``` Out[26]: -``` +```py 1.7976931348623157e+308 ``` @@ -398,14 +398,14 @@ Out[26]: In [27]: -``` +```py sys.float_info.min ``` Out[27]: -``` +```py 2.2250738585072014e-308 ``` @@ -413,14 +413,14 @@ Out[27]: In [28]: -``` +```py sys.float_info.epsilon ``` Out[28]: -``` +```py 2.220446049250313e-16 ``` @@ -430,7 +430,7 @@ Out[28]: In [29]: -``` +```py a = 1 + 2j type(a) @@ -438,7 +438,7 @@ type(a) Out[29]: -``` +```py complex ``` @@ -446,40 +446,40 @@ complex In [30]: -``` +```py a.real ``` Out[30]: -``` +```py 1.0 ``` In [31]: -``` +```py a.imag ``` Out[31]: -``` +```py 2.0 ``` In [32]: -``` +```py a.conjugate() ``` Out[32]: -``` +```py (1-2j) ``` @@ -489,14 +489,14 @@ Out[32]: In [33]: -``` +```py 1 + 2 - (3 * 4 / 6) ** 5 + 7 % 5 ``` Out[33]: -``` +```py -27 ``` @@ -511,27 +511,27 @@ Out[33]: In [34]: -``` +```py 12.3 // 5.2 ``` Out[34]: -``` +```py 2.0 ``` In [35]: -``` +```py 12.3 // -4 ``` Out[35]: -``` +```py -4.0 ``` @@ -541,14 +541,14 @@ Out[35]: In [36]: -``` +```py abs(-12.4) ``` Out[36]: -``` +```py 12.4 ``` @@ -556,14 +556,14 @@ Out[36]: In [37]: -``` +```py round(21.6) ``` Out[37]: -``` +```py 22.0 ``` @@ -571,13 +571,13 @@ Out[37]: In [38]: -``` +```py print min(2, 3, 4, 5) print max(2, 4, 3) ``` -``` +```py 2 4 @@ -589,14 +589,14 @@ print max(2, 4, 3) In [39]: -``` +```py type(max) ``` Out[39]: -``` +```py builtin_function_or_method ``` @@ -604,7 +604,7 @@ builtin_function_or_method In [40]: -``` +```py max = 1 type(max) @@ -612,18 +612,18 @@ type(max) Out[40]: -``` +```py int ``` In [41]: -``` +```py max(4, 5) ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -638,13 +638,13 @@ TypeError: 'int' object is not callable In [42]: -``` +```py print int(12.324) print int(-3.32) ``` -``` +```py 12 -3 @@ -654,12 +654,12 @@ print int(-3.32) In [43]: -``` +```py print float(1.2) ``` -``` +```py 1.2 ``` @@ -672,14 +672,14 @@ print float(1.2) In [44]: -``` +```py 1e-6 ``` Out[44]: -``` +```py 1e-06 ``` @@ -687,14 +687,14 @@ Out[44]: In [45]: -``` +```py 0xFF ``` Out[45]: -``` +```py 255 ``` @@ -702,14 +702,14 @@ Out[45]: In [46]: -``` +```py 067 ``` Out[46]: -``` +```py 55 ``` @@ -717,14 +717,14 @@ Out[46]: In [47]: -``` +```py 0b101010 ``` Out[47]: -``` +```py 42 ``` @@ -734,7 +734,7 @@ Out[47]: In [48]: -``` +```py b = 2.5 b += 2 print b @@ -745,7 +745,7 @@ print b ``` -``` +```py 4.5 9.0 6.0 @@ -758,7 +758,7 @@ print b In [49]: -``` +```py q = True type(q) @@ -766,7 +766,7 @@ type(q) Out[49]: -``` +```py bool ``` @@ -774,20 +774,20 @@ bool In [50]: -``` +```py q = 1 > 2 print q ``` -``` +```py False ``` 常用的比较符号包括: -``` +```py <, >, <=, >=, ==, != ``` @@ -795,7 +795,7 @@ False In [51]: -``` +```py x = 2 1 < x <= 3 @@ -803,7 +803,7 @@ x = 2 Out[51]: -``` +```py True ``` diff --git a/docs/da/010.md b/docs/da/010.md index 37c88432a..b1a799835 100644 --- a/docs/da/010.md +++ b/docs/da/010.md @@ -6,26 +6,26 @@ In [1]: -``` +```py s = "hello, world" print s ``` -``` +```py hello, world ``` In [2]: -``` +```py s = 'hello world' print s ``` -``` +```py hello world ``` @@ -36,7 +36,7 @@ hello world In [3]: -``` +```py s = 'hello ' + 'world' s @@ -44,7 +44,7 @@ s Out[3]: -``` +```py 'hello world' ``` @@ -52,14 +52,14 @@ Out[3]: In [4]: -``` +```py "echo" * 3 ``` Out[4]: -``` +```py 'echoechoecho' ``` @@ -67,14 +67,14 @@ Out[4]: In [5]: -``` +```py len(s) ``` Out[5]: -``` +```py 11 ``` @@ -84,7 +84,7 @@ Out[5]: 跟很多语言一样,**Python**使用以下形式来调用方法: -``` +```py 对象.方法(参数) ``` @@ -94,14 +94,14 @@ s.split()将s按照空格(包括多个空格,制表符`\t`,换行符`\n` In [6]: -``` +```py line = "1 2 3 4 5" numbers = line.split() print numbers ``` -``` +```py ['1', '2', '3', '4', '5'] ``` @@ -110,14 +110,14 @@ s.split(sep)以给定的sep为分隔符对s进行分割。 In [7]: -``` +```py line = "1,2,3,4,5" numbers = line.split(',') print numbers ``` -``` +```py ['1', '2', '3', '4', '5'] ``` @@ -128,7 +128,7 @@ print numbers In [8]: -``` +```py s = ' ' s.join(numbers) @@ -136,13 +136,13 @@ s.join(numbers) Out[8]: -``` +```py '1 2 3 4 5' ``` In [9]: -``` +```py s = ',' s.join(numbers) @@ -150,7 +150,7 @@ s.join(numbers) Out[9]: -``` +```py '1,2,3,4,5' ``` @@ -160,7 +160,7 @@ s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部 In [10]: -``` +```py s = "hello world" s.replace('world', 'python') @@ -168,7 +168,7 @@ s.replace('world', 'python') Out[10]: -``` +```py 'hello python' ``` @@ -176,14 +176,14 @@ Out[10]: In [11]: -``` +```py s ``` Out[11]: -``` +```py 'hello world' ``` @@ -195,14 +195,14 @@ s.lower()方法返回一个将s中的字母全部小写的新字符串。 In [12]: -``` +```py "hello world".upper() ``` Out[12]: -``` +```py 'HELLO WORLD' ``` @@ -210,14 +210,14 @@ Out[12]: In [13]: -``` +```py s = "HELLO WORLD" print s.lower() print s ``` -``` +```py hello world HELLO WORLD @@ -233,7 +233,7 @@ s.rstrip()返回一个将s结尾的多余空格除去的新字符串。 In [14]: -``` +```py s = " hello world " s.strip() @@ -241,7 +241,7 @@ s.strip() Out[14]: -``` +```py 'hello world' ``` @@ -249,40 +249,40 @@ s的值依然不会变化: In [15]: -``` +```py s ``` Out[15]: -``` +```py ' hello world ' ``` In [16]: -``` +```py s.lstrip() ``` Out[16]: -``` +```py 'hello world ' ``` In [17]: -``` +```py s.rstrip() ``` Out[17]: -``` +```py ' hello world' ``` @@ -292,14 +292,14 @@ Out[17]: In [18]: -``` +```py dir(s) ``` Out[18]: -``` +```py ['__add__', '__class__', '__contains__', @@ -379,14 +379,14 @@ Python 用一对 `"""` 或者 `'''` 来生成多行字符串: In [19]: -``` +```py a = """hello world. it is a nice day.""" print a ``` -``` +```py hello world. it is a nice day. @@ -396,14 +396,14 @@ it is a nice day. In [20]: -``` +```py a ``` Out[20]: -``` +```py 'hello world.\nit is a nice day.' ``` @@ -416,7 +416,7 @@ Out[20]: In [21]: -``` +```py a = ("hello, world. " "it's a nice day. " "my name is xxx") @@ -426,13 +426,13 @@ a Out[21]: -``` +```py "hello, world. it's a nice day. my name is xxx" ``` In [22]: -``` +```py a = "hello, world. " \ "it's a nice day. " \ "my name is xxx" @@ -442,7 +442,7 @@ a Out[22]: -``` +```py "hello, world. it's a nice day. my name is xxx" ``` @@ -455,27 +455,27 @@ Out[22]: In [23]: -``` +```py str(1.1 + 2.2) ``` Out[23]: -``` +```py '3.3' ``` In [24]: -``` +```py repr(1.1 + 2.2) ``` Out[24]: -``` +```py '3.3000000000000003' ``` @@ -487,14 +487,14 @@ Out[24]: In [25]: -``` +```py hex(255) ``` Out[25]: -``` +```py '0xff' ``` @@ -502,14 +502,14 @@ Out[25]: In [26]: -``` +```py oct(255) ``` Out[26]: -``` +```py '0377' ``` @@ -517,14 +517,14 @@ Out[26]: In [27]: -``` +```py bin(255) ``` Out[27]: -``` +```py '0b11111111' ``` @@ -532,14 +532,14 @@ Out[27]: In [28]: -``` +```py int('23') ``` Out[28]: -``` +```py 23 ``` @@ -547,40 +547,40 @@ Out[28]: In [29]: -``` +```py int('FF', 16) ``` Out[29]: -``` +```py 255 ``` In [30]: -``` +```py int('377', 8) ``` Out[30]: -``` +```py 255 ``` In [31]: -``` +```py int('11111111', 2) ``` Out[31]: -``` +```py 255 ``` @@ -588,14 +588,14 @@ Out[31]: In [32]: -``` +```py float('3.5') ``` Out[32]: -``` +```py 3.5 ``` @@ -607,14 +607,14 @@ Out[32]: In [33]: -``` +```py '{} {} {}'.format('a', 'b', 'c') ``` Out[33]: -``` +```py 'a b c' ``` @@ -622,14 +622,14 @@ Out[33]: In [34]: -``` +```py '{2} {1} {0}'.format('a', 'b', 'c') ``` Out[34]: -``` +```py 'c b a' ``` @@ -637,14 +637,14 @@ Out[34]: In [35]: -``` +```py '{color} {n} {x}'.format(n=10, x=1.5, color='blue') ``` Out[35]: -``` +```py 'blue 10 1.5' ``` @@ -652,14 +652,14 @@ Out[35]: In [36]: -``` +```py '{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue') ``` Out[36]: -``` +```py 'blue 10 1.5 foo' ``` @@ -667,7 +667,7 @@ Out[36]: In [37]: -``` +```py from math import pi '{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi) @@ -676,7 +676,7 @@ from math import pi Out[37]: -``` +```py 'foo 5 6.28' ``` @@ -686,7 +686,7 @@ Out[37]: In [38]: -``` +```py s = "some numbers:" x = 1.34 y = 2 @@ -697,13 +697,13 @@ t = "%s %f, %d" % (s, x, y) In [39]: -``` +```py t ``` Out[39]: -``` +```py 'some numbers: 1.340000, 2' ``` \ No newline at end of file diff --git a/docs/da/011.md b/docs/da/011.md index a992ebee6..95f48b3bf 100644 --- a/docs/da/011.md +++ b/docs/da/011.md @@ -6,7 +6,7 @@ In [1]: -``` +```py s = "hello world" s[0] @@ -14,7 +14,7 @@ s[0] Out[1]: -``` +```py 'h' ``` @@ -22,14 +22,14 @@ Out[1]: In [2]: -``` +```py s[4] ``` Out[2]: -``` +```py 'o' ``` @@ -37,14 +37,14 @@ Out[2]: In [3]: -``` +```py s[-2] ``` Out[3]: -``` +```py 'l' ``` @@ -52,12 +52,12 @@ Out[3]: In [4]: -``` +```py s[11] ``` -``` +```py --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in () @@ -70,7 +70,7 @@ IndexError: string index out of range 分片用来从序列中提取出想要的子序列,其用法为: -``` +```py var[lower:upper:step] ``` @@ -78,27 +78,27 @@ var[lower:upper:step] In [5]: -``` +```py s ``` Out[5]: -``` +```py 'hello world' ``` In [6]: -``` +```py s[1:3] ``` Out[6]: -``` +```py 'el' ``` @@ -108,14 +108,14 @@ Out[6]: In [7]: -``` +```py s[1:-2] ``` Out[7]: -``` +```py 'ello wor' ``` @@ -125,40 +125,40 @@ lower和upper可以省略,省略lower意味着从开头开始分片,省略up In [8]: -``` +```py s[:3] ``` Out[8]: -``` +```py 'hel' ``` In [9]: -``` +```py s[-3:] ``` Out[9]: -``` +```py 'rld' ``` In [10]: -``` +```py s[:] ``` Out[10]: -``` +```py 'hello world' ``` @@ -166,14 +166,14 @@ Out[10]: In [11]: -``` +```py s[::2] ``` Out[11]: -``` +```py 'hlowrd' ``` @@ -181,14 +181,14 @@ Out[11]: In [12]: -``` +```py s[::-1] ``` Out[12]: -``` +```py 'dlrow olleh' ``` @@ -196,14 +196,14 @@ Out[12]: In [13]: -``` +```py s[:100] ``` Out[13]: -``` +```py 'hello world' ``` diff --git a/docs/da/012.md b/docs/da/012.md index 38c05bcad..98c05809d 100644 --- a/docs/da/012.md +++ b/docs/da/012.md @@ -6,13 +6,13 @@ In [1]: -``` +```py l = [1, 2.0, 'hello'] print l ``` -``` +```py [1, 2.0, 'hello'] ``` @@ -21,7 +21,7 @@ print l In [2]: -``` +```py empty_list = [] empty_list @@ -29,13 +29,13 @@ empty_list Out[2]: -``` +```py [] ``` In [3]: -``` +```py empty_list = list() empty_list @@ -43,7 +43,7 @@ empty_list Out[3]: -``` +```py [] ``` @@ -57,14 +57,14 @@ Out[3]: In [4]: -``` +```py len(l) ``` Out[4]: -``` +```py 3 ``` @@ -74,7 +74,7 @@ Out[4]: In [5]: -``` +```py a = [1, 2, 3] b = [3.2, 'hello'] a + b @@ -83,7 +83,7 @@ a + b Out[5]: -``` +```py [1, 2, 3, 3.2, 'hello'] ``` @@ -91,14 +91,14 @@ Out[5]: In [6]: -``` +```py l * 2 ``` Out[6]: -``` +```py [1, 2.0, 'hello', 1, 2.0, 'hello'] ``` @@ -110,7 +110,7 @@ Out[6]: In [7]: -``` +```py a = [10, 11, 12, 13, 14] a[0] @@ -118,7 +118,7 @@ a[0] Out[7]: -``` +```py 10 ``` @@ -126,14 +126,14 @@ Out[7]: In [8]: -``` +```py a[-1] ``` Out[8]: -``` +```py 14 ``` @@ -141,14 +141,14 @@ Out[8]: In [9]: -``` +```py a[2:-1] ``` Out[9]: -``` +```py [12, 13] ``` @@ -158,14 +158,14 @@ Out[9]: In [10]: -``` +```py s = "hello world" # 把开头的 h 改成大写 s[0] = 'H' ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -180,14 +180,14 @@ TypeError: 'str' object does not support item assignment In [11]: -``` +```py a = [10, 11, 12, 13, 14] a[0] = 100 print a ``` -``` +```py [100, 11, 12, 13, 14] ``` @@ -196,7 +196,7 @@ print a In [12]: -``` +```py a[1:3] = [1, 2] a @@ -204,7 +204,7 @@ a Out[12]: -``` +```py [100, 1, 2, 13, 14] ``` @@ -212,14 +212,14 @@ Out[12]: In [13]: -``` +```py a = [10, 11, 12, 13, 14] a[1:3] = [1, 2, 3, 4] print a ``` -``` +```py [10, 1, 2, 3, 4, 13, 14] ``` @@ -228,7 +228,7 @@ print a In [14]: -``` +```py a = [10, 1, 2, 11, 12] print a[1:3] a[1:3] = [] @@ -236,7 +236,7 @@ print a ``` -``` +```py [1, 2] [10, 11, 12] @@ -246,7 +246,7 @@ print a In [15]: -``` +```py a = [10, 11, 12, 13, 14] a[::2] = [1, 2, 3] a @@ -255,7 +255,7 @@ a Out[15]: -``` +```py [1, 11, 2, 13, 3] ``` @@ -263,12 +263,12 @@ Out[15]: In [16]: -``` +```py a[::2] = [] ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -285,14 +285,14 @@ ValueError: attempt to assign sequence of size 0 to extended slice of size 3 In [17]: -``` +```py a = [1002, 'a', 'b', 'c'] del a[0] print a ``` -``` +```py ['a', 'b', 'c'] ``` @@ -301,7 +301,7 @@ print a In [18]: -``` +```py a = [1002, 'a', 'b', 'c'] del a[1:] a @@ -310,7 +310,7 @@ a Out[18]: -``` +```py [1002] ``` @@ -318,7 +318,7 @@ Out[18]: In [19]: -``` +```py a = ['a', 1, 'b', 2, 'c'] del a[::2] a @@ -327,7 +327,7 @@ a Out[19]: -``` +```py [1, 2] ``` @@ -337,14 +337,14 @@ Out[19]: In [20]: -``` +```py a = [10, 11, 12, 13, 14] print 10 in a print 10 not in a ``` -``` +```py True False @@ -354,14 +354,14 @@ False In [21]: -``` +```py s = 'hello world' print 'he' in s print 'world' not in s ``` -``` +```py True False @@ -371,7 +371,7 @@ False In [22]: -``` +```py a = [10, 'eleven', [12, 13]] a[2] @@ -379,7 +379,7 @@ a[2] Out[22]: -``` +```py [12, 13] ``` @@ -387,14 +387,14 @@ a[2]是列表,可以对它再进行索引: In [23]: -``` +```py a[2][1] ``` Out[23]: -``` +```py 13 ``` @@ -408,7 +408,7 @@ Out[23]: In [24]: -``` +```py a = [11, 12, 13, 12, 11] a.count(11) @@ -416,7 +416,7 @@ a.count(11) Out[24]: -``` +```py 2 ``` @@ -426,14 +426,14 @@ Out[24]: In [25]: -``` +```py a.index(12) ``` Out[25]: -``` +```py 1 ``` @@ -441,12 +441,12 @@ Out[25]: In [26]: -``` +```py a.index(1) ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -463,14 +463,14 @@ ValueError: 1 is not in list In [27]: -``` +```py a = [10, 11, 12] a.append(11) print a ``` -``` +```py [10, 11, 12, 11] ``` @@ -479,13 +479,13 @@ append每次只添加一个元素,并不会因为这个元素是序列而将 In [28]: -``` +```py a.append([11, 12]) print a ``` -``` +```py [10, 11, 12, 11, [11, 12]] ``` @@ -496,14 +496,14 @@ print a In [29]: -``` +```py a = [10, 11, 12, 11] a.extend([1, 2]) print a ``` -``` +```py [10, 11, 12, 11, 1, 2] ``` @@ -514,7 +514,7 @@ print a In [30]: -``` +```py a = [10, 11, 12, 13, 11] # 在索引 3 插入 'a' a.insert(3, 'a') @@ -522,7 +522,7 @@ print a ``` -``` +```py [10, 11, 12, 'a', 13, 11] ``` @@ -533,7 +533,7 @@ print a In [31]: -``` +```py a = [10, 11, 12, 13, 11] # 移除了第一个 11 a.remove(11) @@ -541,7 +541,7 @@ print a ``` -``` +```py [10, 12, 13, 11] ``` @@ -552,7 +552,7 @@ print a In [32]: -``` +```py a = [10, 11, 12, 13, 11] a.pop(2) @@ -560,7 +560,7 @@ a.pop(2) Out[32]: -``` +```py 12 ``` @@ -570,14 +570,14 @@ Out[32]: In [33]: -``` +```py a = [10, 1, 11, 13, 11, 2] a.sort() print a ``` -``` +```py [1, 2, 10, 11, 11, 13] ``` @@ -586,7 +586,7 @@ print a In [34]: -``` +```py a = [10, 1, 11, 13, 11, 2] b = sorted(a) print a @@ -594,7 +594,7 @@ print b ``` -``` +```py [10, 1, 11, 13, 11, 2] [1, 2, 10, 11, 11, 13] @@ -606,14 +606,14 @@ print b In [35]: -``` +```py a = [1, 2, 3, 4, 5, 6] a.reverse() print a ``` -``` +```py [6, 5, 4, 3, 2, 1] ``` @@ -622,7 +622,7 @@ print a In [36]: -``` +```py a = [1, 2, 3, 4, 5, 6] b = a[::-1] print a @@ -630,7 +630,7 @@ print b ``` -``` +```py [1, 2, 3, 4, 5, 6] [6, 5, 4, 3, 2, 1] @@ -640,7 +640,7 @@ print b In [ ]: -``` +```py a.sort? ``` \ No newline at end of file diff --git a/docs/da/013.md b/docs/da/013.md index 6ce56eeda..050ae5bb6 100644 --- a/docs/da/013.md +++ b/docs/da/013.md @@ -4,7 +4,7 @@ In [1]: -``` +```py a = [1,2,3,4] a @@ -12,7 +12,7 @@ a Out[1]: -``` +```py [1, 2, 3, 4] ``` @@ -20,7 +20,7 @@ Out[1]: In [2]: -``` +```py a[0] = 100 a @@ -28,7 +28,7 @@ a Out[2]: -``` +```py [100, 2, 3, 4] ``` @@ -36,7 +36,7 @@ Out[2]: In [3]: -``` +```py a.insert(3, 200) a @@ -44,13 +44,13 @@ a Out[3]: -``` +```py [100, 2, 3, 200, 4] ``` In [4]: -``` +```py a.sort() a @@ -58,7 +58,7 @@ a Out[4]: -``` +```py [2, 3, 4, 100, 200] ``` @@ -66,7 +66,7 @@ Out[4]: In [5]: -``` +```py s = "hello world" s @@ -74,7 +74,7 @@ s Out[5]: -``` +```py 'hello world' ``` @@ -82,12 +82,12 @@ Out[5]: In [6]: -``` +```py s[0] = 'z' ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -100,13 +100,13 @@ TypeError: 'str' object does not support item assignment In [7]: -``` +```py print s.replace('world', 'Mars') print s ``` -``` +```py hello Mars hello world @@ -116,14 +116,14 @@ hello world In [8]: -``` +```py s = "hello world" s = s.replace('world', 'Mars') print s ``` -``` +```py hello Mars ``` @@ -132,7 +132,7 @@ hello Mars In [9]: -``` +```py s = bytearray('abcde') s[1:3] = '12' s @@ -141,7 +141,7 @@ s Out[9]: -``` +```py bytearray(b'a12de') ``` @@ -157,7 +157,7 @@ bytearray(b'a12de') In [10]: -``` +```py a = [1, 2, 3, 4] b = a @@ -167,7 +167,7 @@ b = a In [11]: -``` +```py b[0] = 100 a @@ -175,7 +175,7 @@ a Out[11]: -``` +```py [100, 2, 3, 4] ``` diff --git a/docs/da/014.md b/docs/da/014.md index 0aa5c1530..5c2081e78 100644 --- a/docs/da/014.md +++ b/docs/da/014.md @@ -6,7 +6,7 @@ In [1]: -``` +```py t = (10, 11, 12, 13, 14) t @@ -14,7 +14,7 @@ t Out[1]: -``` +```py (10, 11, 12, 13, 14) ``` @@ -22,27 +22,27 @@ Out[1]: In [2]: -``` +```py t[0] ``` Out[2]: -``` +```py 10 ``` In [3]: -``` +```py t[1:3] ``` Out[3]: -``` +```py (11, 12) ``` @@ -50,13 +50,13 @@ Out[3]: In [4]: -``` +```py # 会报错 t[0] = 1 ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -72,14 +72,14 @@ TypeError: 'tuple' object does not support item assignment In [5]: -``` +```py a = (10,) print a print type(a) ``` -``` +```py (10,) @@ -87,13 +87,13 @@ print type(a) In [6]: -``` +```py a = (10) print type(a) ``` -``` +```py ``` @@ -102,7 +102,7 @@ print type(a) In [7]: -``` +```py a = [10, 11, 12, 13, 14] tuple(a) @@ -110,7 +110,7 @@ tuple(a) Out[7]: -``` +```py (10, 11, 12, 13, 14) ``` @@ -120,27 +120,27 @@ Out[7]: In [8]: -``` +```py a.count(10) ``` Out[8]: -``` +```py 1 ``` In [9]: -``` +```py a.index(12) ``` Out[9]: -``` +```py 2 ``` diff --git a/docs/da/015.md b/docs/da/015.md index 95c30b300..4ece7bc68 100644 --- a/docs/da/015.md +++ b/docs/da/015.md @@ -6,24 +6,24 @@ IPython 中用 `magic` 命令 `%timeit` 来计时。 In [1]: -``` +```py %timeit [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] ``` -``` +```py 1000000 loops, best of 3: 456 ns per loop ``` In [2]: -``` +```py %timeit (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25) ``` -``` +```py 10000000 loops, best of 3: 23 ns per loop ``` @@ -36,7 +36,7 @@ In [2]: In [3]: -``` +```py from numpy.random import rand values = rand(10000,4) lst = [list(row) for row in values] @@ -46,24 +46,24 @@ tup = tuple(tuple(row) for row in values) In [4]: -``` +```py %timeit for row in lst: list(row) ``` -``` +```py 100 loops, best of 3: 4.12 ms per loop ``` In [5]: -``` +```py %timeit for row in tup: tuple(row) ``` -``` +```py 100 loops, best of 3: 2.07 ms per loop ``` @@ -74,12 +74,12 @@ In [5]: In [6]: -``` +```py %timeit for row in lst: a = row[0] + 1 ``` -``` +```py The slowest run took 12.20 times longer than the fastest. This could mean that an intermediate result is being cached 100 loops, best of 3: 3.73 ms per loop @@ -87,12 +87,12 @@ The slowest run took 12.20 times longer than the fastest. This could mean that a In [7]: -``` +```py %timeit for row in tup: a = row[0] + 1 ``` -``` +```py 100 loops, best of 3: 3.82 ms per loop ``` diff --git a/docs/da/016.md b/docs/da/016.md index 5b416de5b..63e11e4aa 100644 --- a/docs/da/016.md +++ b/docs/da/016.md @@ -14,7 +14,7 @@ In [1]: -``` +```py a = {} type(a) @@ -22,13 +22,13 @@ type(a) Out[1]: -``` +```py dict ``` In [2]: -``` +```py a = dict() type(a) @@ -36,7 +36,7 @@ type(a) Out[2]: -``` +```py dict ``` @@ -46,7 +46,7 @@ dict In [3]: -``` +```py a["one"] = "this is number 1" a["two"] = "this is number 2" a @@ -55,7 +55,7 @@ a Out[3]: -``` +```py {'one': 'this is number 1', 'two': 'this is number 2'} ``` @@ -63,14 +63,14 @@ Out[3]: In [4]: -``` +```py a['one'] ``` Out[4]: -``` +```py 'this is number 1' ``` @@ -78,7 +78,7 @@ Out[4]: In [5]: -``` +```py a["one"] = "this is number 1, too" a @@ -86,7 +86,7 @@ a Out[5]: -``` +```py {'one': 'this is number 1, too', 'two': 'this is number 2'} ``` @@ -96,7 +96,7 @@ Out[5]: In [6]: -``` +```py b = {'one': 'this is number 1', 'two': 'this is number 2'} b['one'] @@ -104,7 +104,7 @@ b['one'] Out[6]: -``` +```py 'this is number 1' ``` @@ -114,24 +114,24 @@ Out[6]: In [7]: -``` +```py print a ``` -``` +```py {'two': 'this is number 2', 'one': 'this is number 1, too'} ``` In [8]: -``` +```py print b ``` -``` +```py {'two': 'this is number 2', 'one': 'this is number 1'} ``` @@ -140,13 +140,13 @@ print b In [9]: -``` +```py # 会报错 a[0] ``` -``` +```py --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () @@ -164,7 +164,7 @@ KeyError: 0 In [10]: -``` +```py synonyms = {} synonyms['mutable'] = ['changeable', 'variable', 'varying', 'fluctuating', 'shifting', 'inconsistent', 'unpredictable', 'inconstant', @@ -177,7 +177,7 @@ synonyms Out[10]: -``` +```py {'immutable': ['fixed', 'set', 'rigid', @@ -203,7 +203,7 @@ Out[10]: In [11]: -``` +```py # 定义四个字典 e1 = {'mag': 0.05, 'width': 20} e2 = {'mag': 0.04, 'width': 25} @@ -217,7 +217,7 @@ events Out[11]: -``` +```py {500: {'mag': 0.05, 'width': 20}, 760: {'mag': 0.04, 'width': 25}, 3001: {'mag': 0.05, 'width': 80}, @@ -228,7 +228,7 @@ Out[11]: In [13]: -``` +```py people = [ {'first': 'Sam', 'last': 'Malone', 'name': 35}, {'first': 'Woody', 'last': 'Boyd', 'name': 21}, @@ -241,7 +241,7 @@ people Out[13]: -``` +```py [{'first': 'Sam', 'last': 'Malone', 'name': 35}, {'first': 'Woody', 'last': 'Boyd', 'name': 21}, {'first': 'Norm', 'last': 'Peterson', 'name': 34}, @@ -254,7 +254,7 @@ Out[13]: In [14]: -``` +```py inventory = dict( [('foozelator', 123), ('frombicator', 18), @@ -267,7 +267,7 @@ inventory Out[14]: -``` +```py {'foozelator': 123, 'frombicator': 18, 'snitzelhogen': 23, 'spatzleblock': 34} ``` @@ -275,7 +275,7 @@ Out[14]: In [15]: -``` +```py inventory['frombicator'] += 1 inventory @@ -283,7 +283,7 @@ inventory Out[15]: -``` +```py {'foozelator': 123, 'frombicator': 19, 'snitzelhogen': 23, 'spatzleblock': 34} ``` @@ -293,7 +293,7 @@ Out[15]: In [16]: -``` +```py data = {} data[1.1 + 2.2] = 6.6 # 会报错 @@ -301,7 +301,7 @@ data[3.3] ``` -``` +```py --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () @@ -316,14 +316,14 @@ KeyError: 3.3 In [17]: -``` +```py data ``` Out[17]: -``` +```py {3.3000000000000003: 6.6} ``` @@ -331,7 +331,7 @@ Out[17]: In [19]: -``` +```py connections = {} connections[('New York', 'Seattle')] = 100 connections[('Austin', 'New York')] = 200 @@ -343,13 +343,13 @@ connections[('New York', 'Austin')] = 400 In [20]: -``` +```py print connections[('Austin', 'New York')] print connections[('New York', 'Austin')] ``` -``` +```py 200 400 @@ -361,7 +361,7 @@ print connections[('New York', 'Austin')] 之前已经见过,用索引可以找到一个键对应的值,但是当字典中没有这个键的时候,Python会报错,这时候可以使用字典的 `get` 方法来处理这种情况,其用法如下: -``` +```py `d.get(key, default = None)` ``` @@ -369,7 +369,7 @@ print connections[('New York', 'Austin')] In [21]: -``` +```py a = {} a["one"] = "this is number 1" a["two"] = "this is number 2" @@ -380,12 +380,12 @@ a["two"] = "this is number 2" In [22]: -``` +```py a["three"] ``` -``` +```py --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () @@ -398,12 +398,12 @@ KeyError: 'three' In [24]: -``` +```py print a.get("three") ``` -``` +```py None ``` @@ -412,14 +412,14 @@ None In [25]: -``` +```py a.get("three", "undefined") ``` Out[25]: -``` +```py 'undefined' ``` @@ -427,7 +427,7 @@ Out[25]: `pop` 方法可以用来弹出字典中某个键对应的值,同时也可以指定默认参数: -``` +```py `d.pop(key, default = None)` ``` @@ -435,14 +435,14 @@ Out[25]: In [26]: -``` +```py a ``` Out[26]: -``` +```py {'one': 'this is number 1', 'two': 'this is number 2'} ``` @@ -450,27 +450,27 @@ Out[26]: In [27]: -``` +```py a.pop("two") ``` Out[27]: -``` +```py 'this is number 2' ``` In [28]: -``` +```py a ``` Out[28]: -``` +```py {'one': 'this is number 1'} ``` @@ -478,14 +478,14 @@ Out[28]: In [29]: -``` +```py a.pop("two", 'not exist') ``` Out[29]: -``` +```py 'not exist' ``` @@ -493,7 +493,7 @@ Out[29]: In [30]: -``` +```py del a["one"] a @@ -501,7 +501,7 @@ a Out[30]: -``` +```py {} ``` @@ -509,7 +509,7 @@ Out[30]: 之前已经知道,可以通过索引来插入、修改单个键值对,但是如果想对多个键值对进行操作,这种方法就显得比较麻烦,好在有 `update` 方法: -``` +```py `d.update(newd)` ``` @@ -517,7 +517,7 @@ Out[30]: In [31]: -``` +```py person = {} person['first'] = "Jmes" person['last'] = "Maxwell" @@ -526,7 +526,7 @@ print person ``` -``` +```py {'born': 1831, 'last': 'Maxwell', 'first': 'Jmes'} ``` @@ -535,14 +535,14 @@ print person In [32]: -``` +```py person_modifications = {'first': 'James', 'middle': 'Clerk'} person.update(person_modifications) print person ``` -``` +```py {'middle': 'Clerk', 'born': 1831, 'last': 'Maxwell', 'first': 'James'} ``` @@ -551,7 +551,7 @@ print person In [33]: -``` +```py barn = {'cows': 1, 'dogs': 5, 'cats': 3} ``` @@ -560,45 +560,45 @@ barn = {'cows': 1, 'dogs': 5, 'cats': 3} In [35]: -``` +```py 'chickens' in barn ``` Out[35]: -``` +```py False ``` In [34]: -``` +```py 'cows' in barn ``` Out[34]: -``` +```py True ``` ### `keys` 方法,`values` 方法和`items` 方法 -``` +```py `d.keys()` ``` 返回一个由所有键组成的列表; -``` +```py `d.values()` ``` 返回一个由所有值组成的列表; -``` +```py `d.items()` ``` @@ -606,39 +606,39 @@ True In [36]: -``` +```py barn.keys() ``` Out[36]: -``` +```py ['cows', 'cats', 'dogs'] ``` In [37]: -``` +```py barn.values() ``` Out[37]: -``` +```py [1, 3, 5] ``` In [38]: -``` +```py barn.items() ``` Out[38]: -``` +```py [('cows', 1), ('cats', 3), ('dogs', 5)] ``` \ No newline at end of file diff --git a/docs/da/017.md b/docs/da/017.md index 9b3e9276f..2d90bacd6 100644 --- a/docs/da/017.md +++ b/docs/da/017.md @@ -10,7 +10,7 @@ In [1]: -``` +```py a = set() type(a) @@ -18,7 +18,7 @@ type(a) Out[1]: -``` +```py set ``` @@ -26,7 +26,7 @@ set In [2]: -``` +```py a = set([1, 2, 3, 1]) a @@ -34,7 +34,7 @@ a Out[2]: -``` +```py {1, 2, 3} ``` @@ -44,7 +44,7 @@ Out[2]: In [3]: -``` +```py a = {1, 2, 3, 1} a @@ -52,7 +52,7 @@ a Out[3]: -``` +```py {1, 2, 3} ``` @@ -60,7 +60,7 @@ Out[3]: In [4]: -``` +```py s = {} type(s) @@ -68,7 +68,7 @@ type(s) Out[4]: -``` +```py dict ``` @@ -78,7 +78,7 @@ dict In [5]: -``` +```py a = {1, 2, 3, 4} b = {3, 4, 5, 6} @@ -92,40 +92,40 @@ b = {3, 4, 5, 6} In [6]: -``` +```py a.union(b) ``` Out[6]: -``` +```py {1, 2, 3, 4, 5, 6} ``` In [7]: -``` +```py b.union(a) ``` Out[7]: -``` +```py {1, 2, 3, 4, 5, 6} ``` In [8]: -``` +```py a | b ``` Out[8]: -``` +```py {1, 2, 3, 4, 5, 6} ``` @@ -137,51 +137,51 @@ Out[8]: In [9]: -``` +```py a.intersection(b) ``` Out[9]: -``` +```py {3, 4} ``` In [10]: -``` +```py b.intersection(a) ``` Out[10]: -``` +```py {3, 4} ``` In [11]: -``` +```py a & b ``` Out[11]: -``` +```py {3, 4} ``` In [12]: -``` +```py print(a & b) ``` -``` +```py set([3, 4]) ``` @@ -196,27 +196,27 @@ set([3, 4]) In [13]: -``` +```py a.difference(b) ``` Out[13]: -``` +```py {1, 2} ``` In [14]: -``` +```py a - b ``` Out[14]: -``` +```py {1, 2} ``` @@ -224,27 +224,27 @@ Out[14]: In [15]: -``` +```py b.difference(a) ``` Out[15]: -``` +```py {5, 6} ``` In [16]: -``` +```py b - a ``` Out[16]: -``` +```py {5, 6} ``` @@ -256,40 +256,40 @@ Out[16]: In [17]: -``` +```py a.symmetric_difference(b) ``` Out[17]: -``` +```py {1, 2, 5, 6} ``` In [18]: -``` +```py b.symmetric_difference(a) ``` Out[18]: -``` +```py {1, 2, 5, 6} ``` In [19]: -``` +```py a ^ b ``` Out[19]: -``` +```py {1, 2, 5, 6} ``` @@ -299,7 +299,7 @@ Out[19]: In [20]: -``` +```py a = {1, 2, 3} b = {1, 2} @@ -309,27 +309,27 @@ b = {1, 2} In [21]: -``` +```py b.issubset(a) ``` Out[21]: -``` +```py True ``` In [22]: -``` +```py b <= a ``` Out[22]: -``` +```py True ``` @@ -337,27 +337,27 @@ True In [23]: -``` +```py a.issuperset(b) ``` Out[23]: -``` +```py True ``` In [24]: -``` +```py a >= b ``` Out[24]: -``` +```py True ``` @@ -365,14 +365,14 @@ True In [25]: -``` +```py a <= a ``` Out[25]: -``` +```py True ``` @@ -380,14 +380,14 @@ True In [26]: -``` +```py a < a ``` Out[26]: -``` +```py False ``` @@ -397,7 +397,7 @@ False 跟列表的 `append` 方法类似,用来向集合添加单个元素。 -``` +```py s.add(a) ``` @@ -405,7 +405,7 @@ s.add(a) In [27]: -``` +```py t = {1, 2, 3} t.add(5) t @@ -414,7 +414,7 @@ t Out[27]: -``` +```py {1, 2, 3, 5} ``` @@ -422,7 +422,7 @@ Out[27]: In [28]: -``` +```py t.add(3) t @@ -430,7 +430,7 @@ t Out[28]: -``` +```py {1, 2, 3, 5} ``` @@ -438,7 +438,7 @@ Out[28]: 跟列表的`extend`方法类似,用来向集合添加多个元素。 -``` +```py s.update(seq) ``` @@ -446,7 +446,7 @@ s.update(seq) In [29]: -``` +```py t.update([5, 6, 7]) t @@ -454,13 +454,13 @@ t Out[29]: -``` +```py {1, 2, 3, 5, 6, 7} ``` ### `remove` 方法移除单个元素 -``` +```py s.remove(ob) ``` @@ -468,7 +468,7 @@ s.remove(ob) In [30]: -``` +```py t.remove(1) t @@ -476,18 +476,18 @@ t Out[30]: -``` +```py {2, 3, 5, 6, 7} ``` In [31]: -``` +```py t.remove(10) ``` -``` +```py --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () @@ -502,39 +502,39 @@ KeyError: 10 In [32]: -``` +```py t.pop() ``` Out[32]: -``` +```py {3, 5, 6, 7} ``` In [33]: -``` +```py print t ``` -``` +```py set([3, 5, 6, 7]) ``` In [34]: -``` +```py s = set() # 报错 s.pop() ``` -``` +```py --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () @@ -551,21 +551,21 @@ KeyError: 'pop from an empty set' In [35]: -``` +```py t.discard(3) ``` In [36]: -``` +```py t ``` Out[36]: -``` +```py {5, 6, 7} ``` @@ -573,27 +573,27 @@ Out[36]: In [37]: -``` +```py t.discard(20) ``` In [38]: -``` +```py t ``` Out[38]: -``` +```py {5, 6, 7} ``` ### difference_update方法 -``` +```py a.difference_update(b) ``` diff --git a/docs/da/018.md b/docs/da/018.md index c319af89e..86e464673 100644 --- a/docs/da/018.md +++ b/docs/da/018.md @@ -6,7 +6,7 @@ In [1]: -``` +```py s = frozenset([1, 2, 3, 'a', 1]) s @@ -14,7 +14,7 @@ s Out[1]: -``` +```py frozenset({1, 2, 3, 'a'}) ``` @@ -24,7 +24,7 @@ frozenset({1, 2, 3, 'a'}) In [2]: -``` +```py flight_distance = {} city_pair = frozenset(['Los Angeles', 'New York']) flight_distance[city_pair] = 2498 @@ -36,7 +36,7 @@ flight_distance Out[2]: -``` +```py {frozenset({'Austin', 'New York'}): 1515, frozenset({'Austin', 'Los Angeles'}): 1233, frozenset({'Los Angeles', 'New York'}): 2498} @@ -46,26 +46,26 @@ Out[2]: In [3]: -``` +```py flight_distance[frozenset(['New York','Austin'])] ``` Out[3]: -``` +```py 1515 ``` In [4]: -``` +```py flight_distance[frozenset(['Austin','New York'])] ``` Out[4]: -``` +```py 1515 ``` \ No newline at end of file diff --git a/docs/da/019.md b/docs/da/019.md index f7fb39283..e0eb8beaf 100644 --- a/docs/da/019.md +++ b/docs/da/019.md @@ -4,7 +4,7 @@ In [1]: -``` +```py x = [1, 2, 3] y = x x[1] = 100 @@ -12,7 +12,7 @@ print y ``` -``` +```py [1, 100, 3] ``` @@ -23,7 +23,7 @@ print y 先来看这一段代码在**Python**中的执行过程。 -``` +```py x = 500 y = x y = 'foo' @@ -59,7 +59,7 @@ y = 'foo' 对这一过程进行验证,可以使用 `id` 函数。 -``` +```py id(x) ``` @@ -67,7 +67,7 @@ id(x) In [2]: -``` +```py x = 500 id(x) @@ -75,13 +75,13 @@ id(x) Out[2]: -``` +```py 48220272L ``` In [3]: -``` +```py y = x id(y) @@ -89,7 +89,7 @@ id(y) Out[3]: -``` +```py 48220272L ``` @@ -97,14 +97,14 @@ Out[3]: In [4]: -``` +```py x is y ``` Out[4]: -``` +```py True ``` @@ -112,7 +112,7 @@ True In [5]: -``` +```py y = 'foo' id(y) @@ -120,20 +120,20 @@ id(y) Out[5]: -``` +```py 39148320L ``` In [6]: -``` +```py x is y ``` Out[6]: -``` +```py False ``` @@ -141,7 +141,7 @@ False In [7]: -``` +```py x = 500 id(x) @@ -149,13 +149,13 @@ id(x) Out[7]: -``` +```py 48220296L ``` In [8]: -``` +```py y = 500 id(y) @@ -163,20 +163,20 @@ id(y) Out[8]: -``` +```py 48220224L ``` In [9]: -``` +```py x is y ``` Out[9]: -``` +```py False ``` @@ -184,7 +184,7 @@ False In [10]: -``` +```py x = 2 id(x) @@ -192,13 +192,13 @@ id(x) Out[10]: -``` +```py 6579504L ``` In [11]: -``` +```py y = 2 id(y) @@ -206,20 +206,20 @@ id(y) Out[11]: -``` +```py 6579504L ``` In [12]: -``` +```py x is y ``` Out[12]: -``` +```py True ``` @@ -227,7 +227,7 @@ True 现在来看另一段代码: -``` +```py x = [500, 501, 502] y = x y[1] = 600 @@ -292,7 +292,7 @@ Python为3个PyInt分配内存 `pos1` , `pos2` , `pos3` (不可变), In [13]: -``` +```py x = [500, 501, 502] print id(x[0]) print id(x[1]) @@ -301,7 +301,7 @@ print id(x) ``` -``` +```py 48220224 48220248 48220200 @@ -313,27 +313,27 @@ print id(x) In [14]: -``` +```py y = x print id(y) ``` -``` +```py 54993032 ``` In [15]: -``` +```py x is y ``` Out[15]: -``` +```py True ``` @@ -341,13 +341,13 @@ True In [16]: -``` +```py y[1] = 600 print id(y) ``` -``` +```py 54993032 ``` @@ -356,13 +356,13 @@ print id(y) In [17]: -``` +```py print id(x[1]) print id(y[1]) ``` -``` +```py 48220272 48220272 @@ -372,14 +372,14 @@ print id(y[1]) In [18]: -``` +```py y = [700, 800] print id(y) print id(x) ``` -``` +```py 54995272 54993032 diff --git a/docs/da/020.md b/docs/da/020.md index 2cdefe50b..555197cee 100644 --- a/docs/da/020.md +++ b/docs/da/020.md @@ -6,7 +6,7 @@ In [1]: -``` +```py x = 0.5 if x > 0: print "Hey!" @@ -14,7 +14,7 @@ if x > 0: ``` -``` +```py Hey! x is positive @@ -26,7 +26,7 @@ x is positive 上面例子中的这两条语句: -``` +```py print "Hey!" print "x is positive" @@ -40,7 +40,7 @@ print "Hey!" In [2]: -``` +```py x = 0.5 if x > 0: print "Hey!" @@ -50,7 +50,7 @@ print "This isn't part of the block, and will always print." ``` -``` +```py Hey! x is positive This is still part of the block @@ -62,7 +62,7 @@ This isn't part of the block, and will always print. In [3]: -``` +```py x = -0.5 if x > 0: print "Hey!" @@ -72,7 +72,7 @@ print "This isn't part of the block, and will always print." ``` -``` +```py This isn't part of the block, and will always print. ``` @@ -81,7 +81,7 @@ This isn't part of the block, and will always print. 一个完整的 `if` 结构通常如下所示(注意:条件后的 `:` 是必须要的,缩进值需要一样): -``` +```py if : @@ -97,7 +97,7 @@ else: In [4]: -``` +```py x = 0 if x > 0: print "x is positive" @@ -108,7 +108,7 @@ else: ``` -``` +```py x is zero ``` @@ -121,7 +121,7 @@ x is zero In [5]: -``` +```py x = 10 y = -5 x > 0 and y < 0 @@ -130,33 +130,33 @@ x > 0 and y < 0 Out[5]: -``` +```py True ``` In [6]: -``` +```py not x > 0 ``` Out[6]: -``` +```py False ``` In [7]: -``` +```py x < 0 or y < 0 ``` Out[7]: -``` +```py True ``` @@ -164,7 +164,7 @@ True In [8]: -``` +```py year = 1900 if year % 400 == 0: print "This is a leap year!" @@ -176,7 +176,7 @@ else: ``` -``` +```py This is not a leap year. ``` @@ -194,7 +194,7 @@ This is not a leap year. In [9]: -``` +```py mylist = [3, 1, 4, 1, 5, 9] if mylist: print "The first element is:", mylist[0] @@ -203,7 +203,7 @@ else: ``` -``` +```py The first element is: 3 ``` @@ -212,7 +212,7 @@ The first element is: 3 In [10]: -``` +```py mylist = [] if mylist: print "The first element is:", mylist[0] @@ -221,7 +221,7 @@ else: ``` -``` +```py There is no first element. ``` diff --git a/docs/da/021.md b/docs/da/021.md index c1acf0a74..ec09e3a34 100644 --- a/docs/da/021.md +++ b/docs/da/021.md @@ -4,7 +4,7 @@ ## while 循环 -``` +```py while : ``` @@ -15,7 +15,7 @@ while : In [1]: -``` +```py i = 0 total = 0 while i < 1000000: @@ -25,7 +25,7 @@ print total ``` -``` +```py 499999500000 ``` @@ -34,7 +34,7 @@ print total In [2]: -``` +```py plays = set(['Hamlet', 'Macbeth', 'King Lear']) while plays: play = plays.pop() @@ -42,7 +42,7 @@ while plays: ``` -``` +```py Perform King Lear Perform Macbeth Perform Hamlet @@ -53,7 +53,7 @@ Perform Hamlet ## for 循环 -``` +```py for in : ``` @@ -64,14 +64,14 @@ for in : In [3]: -``` +```py plays = set(['Hamlet', 'Macbeth', 'King Lear']) for play in plays: print 'Perform', play ``` -``` +```py Perform King Lear Perform Macbeth Perform Hamlet @@ -84,7 +84,7 @@ Perform Hamlet In [4]: -``` +```py total = 0 for i in range(100000): total += i @@ -92,7 +92,7 @@ print total ``` -``` +```py 4999950000 ``` @@ -105,7 +105,7 @@ print total In [5]: -``` +```py total = 0 for i in xrange(100000): total += i @@ -113,7 +113,7 @@ print total ``` -``` +```py 4999950000 ``` @@ -122,24 +122,24 @@ print total In [6]: -``` +```py %timeit for i in xrange(1000000): i = i ``` -``` +```py 10 loops, best of 3: 40.7 ms per loop ``` In [7]: -``` +```py %timeit for i in range(1000000): i = i ``` -``` +```py 10 loops, best of 3: 96.6 ms per loop ``` @@ -154,7 +154,7 @@ In [7]: In [8]: -``` +```py values = [7, 6, 4, 7, 19, 2, 1] for i in values: if i % 2 != 0: @@ -164,7 +164,7 @@ for i in values: ``` -``` +```py 3 2 1 @@ -177,7 +177,7 @@ for i in values: In [9]: -``` +```py command_list = ['start', 'process', 'process', @@ -194,7 +194,7 @@ while command_list: ``` -``` +```py start process process @@ -215,7 +215,7 @@ process In [10]: -``` +```py values = [7, 6, 4, 7, 19, 2, 1] for x in values: if x <= 10: @@ -226,7 +226,7 @@ else: ``` -``` +```py Found: 7 ``` @@ -235,7 +235,7 @@ Found: 7 In [11]: -``` +```py values = [11, 12, 13, 100] for x in values: if x <= 10: @@ -246,7 +246,7 @@ else: ``` -``` +```py All values greater than 10 ``` \ No newline at end of file diff --git a/docs/da/022.md b/docs/da/022.md index 31d6a26e9..549845485 100644 --- a/docs/da/022.md +++ b/docs/da/022.md @@ -4,7 +4,7 @@ In [1]: -``` +```py values = [10, 21, 4, 7, 12] squares = [] for x in values: @@ -13,7 +13,7 @@ print squares ``` -``` +```py [100, 441, 16, 49, 144] ``` @@ -22,14 +22,14 @@ print squares In [2]: -``` +```py values = [10, 21, 4, 7, 12] squares = [x**2 for x in values] print squares ``` -``` +```py [100, 441, 16, 49, 144] ``` @@ -40,14 +40,14 @@ print squares In [3]: -``` +```py values = [10, 21, 4, 7, 12] squares = [x**2 for x in values if x <= 10] print squares ``` -``` +```py [100, 16, 49] ``` @@ -56,7 +56,7 @@ print squares In [4]: -``` +```py square_set = {x**2 for x in values if x <= 10} print(square_set) square_dict = {x: x**2 for x in values if x <= 10} @@ -64,7 +64,7 @@ print(square_dict) ``` -``` +```py set([16, 49, 100]) {10: 100, 4: 16, 7: 49} @@ -74,13 +74,13 @@ set([16, 49, 100]) In [5]: -``` +```py total = sum([x**2 for x in values if x <= 10]) print(total) ``` -``` +```py 165 ``` @@ -91,13 +91,13 @@ print(total) In [6]: -``` +```py total = sum(x**2 for x in values if x <= 10) print(total) ``` -``` +```py 165 ``` @@ -108,31 +108,31 @@ print(total) In [7]: -``` +```py x = range(1000000) ``` In [8]: -``` +```py %timeit total = sum([i**2 for i in x]) ``` -``` +```py 1 loops, best of 3: 3.86 s per loop ``` In [9]: -``` +```py %timeit total = sum(i**2 for i in x) ``` -``` +```py 1 loops, best of 3: 2.58 s per loop ``` \ No newline at end of file diff --git a/docs/da/023.md b/docs/da/023.md index 99dd320f3..ef53a5af5 100644 --- a/docs/da/023.md +++ b/docs/da/023.md @@ -8,7 +8,7 @@ In [1]: -``` +```py def add(x, y): """Add two numbers""" a = x + y @@ -32,13 +32,13 @@ def add(x, y): In [2]: -``` +```py print add(2, 3) print add('foo', 'bar') ``` -``` +```py 5 foobar @@ -48,12 +48,12 @@ foobar In [3]: -``` +```py print add(2, "foo") ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -72,12 +72,12 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str' In [4]: -``` +```py print add(1, 2, 3) ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -88,12 +88,12 @@ TypeError: add() takes exactly 2 arguments (3 given) In [5]: -``` +```py print add(1) ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -106,13 +106,13 @@ TypeError: add() takes exactly 2 arguments (1 given) In [6]: -``` +```py print add(x=2, y=3) print add(y="foo", x="bar") ``` -``` +```py 5 barfoo @@ -122,12 +122,12 @@ barfoo In [7]: -``` +```py print add(2, y=3) ``` -``` +```py 5 ``` @@ -138,7 +138,7 @@ print add(2, y=3) In [8]: -``` +```py def quad(x, a=1, b=0, c=0): return a*x**2 + b*x + c @@ -148,12 +148,12 @@ def quad(x, a=1, b=0, c=0): In [9]: -``` +```py print quad(2.0) ``` -``` +```py 4.0 ``` @@ -162,24 +162,24 @@ print quad(2.0) In [10]: -``` +```py print quad(2.0, b=3) ``` -``` +```py 10.0 ``` In [11]: -``` +```py print quad(2.0, 2, c=4) ``` -``` +```py 12.0 ``` @@ -190,12 +190,12 @@ print quad(2.0, 2, c=4) In [12]: -``` +```py print quad(2.0, 2, a=2) ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -210,7 +210,7 @@ TypeError: quad() got multiple values for keyword argument 'a' In [13]: -``` +```py def add(x, *args): total = x for arg in args: @@ -223,13 +223,13 @@ def add(x, *args): In [14]: -``` +```py print add(1, 2, 3, 4) print add(1, 2) ``` -``` +```py 10 3 @@ -239,7 +239,7 @@ print add(1, 2) In [15]: -``` +```py def add(x, **kwargs): total = x for arg, value in kwargs.items(): @@ -253,12 +253,12 @@ def add(x, **kwargs): In [16]: -``` +```py print add(10, y=11, z=12, w=13) ``` -``` +```py adding y adding z adding w @@ -270,7 +270,7 @@ adding w In [17]: -``` +```py def foo(*args, **kwargs): print args, kwargs @@ -278,7 +278,7 @@ foo(2, 3, x='bar', z=10) ``` -``` +```py (2, 3) {'x': 'bar', 'z': 10} ``` @@ -291,7 +291,7 @@ foo(2, 3, x='bar', z=10) In [18]: -``` +```py from math import atan2 def to_polar(x, y): @@ -304,7 +304,7 @@ print r, theta ``` -``` +```py 5.0 0.927295218002 ``` @@ -313,19 +313,19 @@ print r, theta In [19]: -``` +```py print to_polar(3, 4) ``` -``` +```py (5.0, 0.9272952180016122) ``` 因为这个元组中有两个值,所以可以使用 -``` +```py r, theta = to_polar(3, 4) ``` @@ -335,13 +335,13 @@ r, theta = to_polar(3, 4) In [20]: -``` +```py a, b, c = [1, 2, 3] print a, b, c ``` -``` +```py 1 2 3 ``` @@ -350,7 +350,7 @@ print a, b, c In [21]: -``` +```py def add(x, y): """Add two numbers""" a = x + y @@ -361,7 +361,7 @@ print add(*z) ``` -``` +```py 5 ``` @@ -372,7 +372,7 @@ print add(*z) In [22]: -``` +```py def add(x, y): """Add two numbers""" a = x + y @@ -383,7 +383,7 @@ print add(**w) ``` -``` +```py 5 ``` @@ -394,7 +394,7 @@ print add(**w) In [23]: -``` +```py def sqr(x): return x ** 2 @@ -403,14 +403,14 @@ print map(sqr, a) ``` -``` +```py [4, 9, 16] ``` 其用法为: -``` +```py map(aFun, aSeq) ``` @@ -420,7 +420,7 @@ map(aFun, aSeq) In [24]: -``` +```py def add(x, y): return x + y @@ -430,7 +430,7 @@ print map(add,a,b) ``` -``` +```py [12, 8, 7] ``` \ No newline at end of file diff --git a/docs/da/024.md b/docs/da/024.md index 08b044210..e4aa7d110 100644 --- a/docs/da/024.md +++ b/docs/da/024.md @@ -6,7 +6,7 @@ Python会将所有 `.py` 结尾的文件认定为Python代码文件,考虑下 In [1]: -``` +```py %%writefile ex1.py PI = 3.1416 @@ -22,7 +22,7 @@ print sum(w), PI ``` -``` +```py Overwriting ex1.py ``` @@ -31,12 +31,12 @@ Overwriting ex1.py In [2]: -``` +```py %run ex1.py ``` -``` +```py 6 3.1416 ``` @@ -45,26 +45,26 @@ In [2]: In [3]: -``` +```py import ex1 ``` -``` +```py 6 3.1416 ``` In [4]: -``` +```py ex1 ``` Out[4]: -``` +```py ``` @@ -72,7 +72,7 @@ Out[4]: `ex1.py` 中所有的变量都被载入了当前环境中,不过要使用 -``` +```py ex1.变量名 ``` @@ -80,32 +80,32 @@ ex1.变量名 In [5]: -``` +```py print ex1.PI ``` -``` +```py 3.1416 ``` In [6]: -``` +```py ex1.PI = 3.141592653 print ex1.PI ``` -``` +```py 3.141592653 ``` 还可以用 -``` +```py ex1.函数名 ``` @@ -113,12 +113,12 @@ ex1.函数名 In [7]: -``` +```py print ex1.sum([2, 3, 4]) ``` -``` +```py 9 ``` @@ -129,7 +129,7 @@ print ex1.sum([2, 3, 4]) In [8]: -``` +```py import ex1 ``` @@ -138,19 +138,19 @@ import ex1 In [9]: -``` +```py reload(ex1) ``` -``` +```py 6 3.1416 ``` Out[9]: -``` +```py ``` @@ -158,7 +158,7 @@ Out[9]: In [10]: -``` +```py import os os.remove('ex1.py') @@ -172,7 +172,7 @@ os.remove('ex1.py') In [11]: -``` +```py %%writefile ex2.py PI = 3.1416 @@ -200,7 +200,7 @@ if __name__ == '__main__': ``` -``` +```py Writing ex2.py ``` @@ -209,12 +209,12 @@ Writing ex2.py In [12]: -``` +```py %run ex2.py ``` -``` +```py test passed. ``` @@ -223,7 +223,7 @@ test passed. In [13]: -``` +```py import ex2 ``` @@ -232,14 +232,14 @@ import ex2 In [14]: -``` +```py ex2.PI ``` Out[14]: -``` +```py 3.1416 ``` @@ -247,7 +247,7 @@ Out[14]: In [15]: -``` +```py import ex2 as e2 e2.PI @@ -255,7 +255,7 @@ e2.PI Out[15]: -``` +```py 3.1416 ``` @@ -265,7 +265,7 @@ Out[15]: In [16]: -``` +```py from ex2 import add, PI ``` @@ -274,14 +274,14 @@ from ex2 import add, PI In [17]: -``` +```py add(2, 3) ``` Out[17]: -``` +```py 5 ``` @@ -289,7 +289,7 @@ Out[17]: In [18]: -``` +```py from ex2 import * add(3, 4.5) @@ -297,7 +297,7 @@ add(3, 4.5) Out[18]: -``` +```py 7.5 ``` @@ -307,7 +307,7 @@ Out[18]: In [19]: -``` +```py import os os.remove('ex2.py') @@ -325,7 +325,7 @@ foo/ 这意味着 foo 是一个包,我们可以这样导入其中的内容: -``` +```py from foo.bar import func from foo.baz import zap diff --git a/docs/da/025.md b/docs/da/025.md index 66b7afcf5..6ed8b0333 100644 --- a/docs/da/025.md +++ b/docs/da/025.md @@ -6,7 +6,7 @@ 看下面这段代码: -``` +```py import math while True: @@ -25,7 +25,7 @@ while True: In [1]: -``` +```py import math while True: @@ -38,12 +38,12 @@ while True: ``` -``` +```py > -1 ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -59,7 +59,7 @@ ValueError: math domain error 一旦报错,程序就会停止执行,如果不希望程序停止执行,那么我们可以添加一对 `try & except`: -``` +```py import math while True: @@ -81,7 +81,7 @@ while True: In [2]: -``` +```py import math while True: @@ -97,7 +97,7 @@ while True: ``` -``` +```py > -1 the value must be greater than 0 > 0 @@ -110,7 +110,7 @@ log10(1.0) = 0.0 ## 捕捉不同的错误类型 -``` +```py import math while True: @@ -130,7 +130,7 @@ while True: In [3]: -``` +```py import math while True: @@ -146,12 +146,12 @@ while True: ``` -``` +```py > 1 ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -172,7 +172,7 @@ ZeroDivisionError: float division by zero In [4]: -``` +```py import math while True: @@ -188,7 +188,7 @@ while True: ``` -``` +```py > 1 invalid value > 0 @@ -207,7 +207,7 @@ invalid value In [5]: -``` +```py import math while True: @@ -223,7 +223,7 @@ while True: ``` -``` +```py > 1 invalid value > -1 @@ -238,7 +238,7 @@ invalid value In [6]: -``` +```py import math while True: @@ -256,7 +256,7 @@ while True: ``` -``` +```py > 1 the value must not be 1 > -1 @@ -273,7 +273,7 @@ the value must be greater than 0 In [7]: -``` +```py import math while True: @@ -293,7 +293,7 @@ while True: ``` -``` +```py > 1 the value must not be 1 > -1 @@ -310,12 +310,12 @@ the value must be greater than 0 In [8]: -``` +```py float('a') ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -328,7 +328,7 @@ ValueError: could not convert string to float: a In [9]: -``` +```py import math while True: @@ -351,7 +351,7 @@ while True: ``` -``` +```py > 1 the value must not be 1 > -1 @@ -366,19 +366,19 @@ could not convert 'aa' to float 这里,`exc.message` 显示的内容是异常对应的说明,例如 -``` +```py ValueError: could not convert string to float: a ``` 对应的 `message` 是 -``` +```py could not convert string to float: a ``` 当我们使用 `except Exception` 时,会捕获所有的 `Exception` 和它派生出来的子类,但不是所有的异常都是从 `Exception` 类派生出来的,可能会出现一些不能捕获的情况,因此,更加一般的做法是使用这样的形式: -``` +```py try: pass except: @@ -394,7 +394,7 @@ except: In [10]: -``` +```py class CommandError(ValueError): pass @@ -404,7 +404,7 @@ class CommandError(ValueError): In [11]: -``` +```py valid_commands = {'start', 'stop', 'pause'} while True: @@ -414,12 +414,12 @@ while True: ``` -``` +```py > bad command ``` -``` +```py --------------------------------------------------------------------------- CommandError Traceback (most recent call last) in () @@ -434,7 +434,7 @@ CommandError: Invalid commmand: bad command 我们可以使用 `try/except` 块来捕捉这个异常: -``` +```py valid_commands = {'start', 'stop', 'pause'} while True: @@ -457,7 +457,7 @@ try/catch 块还有一个可选的关键词 finally。 In [12]: -``` +```py try: print 1 finally: @@ -465,7 +465,7 @@ finally: ``` -``` +```py 1 finally was called. @@ -475,7 +475,7 @@ finally was called. In [13]: -``` +```py try: print 1 / 0 finally: @@ -483,12 +483,12 @@ finally: ``` -``` +```py finally was called. ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -504,7 +504,7 @@ ZeroDivisionError: integer division or modulo by zero In [14]: -``` +```py try: print 1 / 0 except ZeroDivisionError: @@ -514,7 +514,7 @@ finally: ``` -``` +```py divide by 0. finally was called. diff --git a/docs/da/026.md b/docs/da/026.md index abc77700c..52a2a2dd9 100644 --- a/docs/da/026.md +++ b/docs/da/026.md @@ -6,20 +6,20 @@ In [1]: -``` +```py import warnings ``` 在需要的地方,我们使用 `warnings` 中的 `warn` 函数: -``` +```py warn(msg, WarningType = UserWarning) ``` In [2]: -``` +```py def month_warning(m): if not 1<= m <= 12: msg = "month (%d) is not between 1 and 12" % m @@ -29,14 +29,14 @@ month_warning(13) ``` -``` +```py c:\Anaconda\lib\site-packages\IPython\kernel\__main__.py:4: RuntimeWarning: month (13) is not between 1 and 12 ``` 有时候我们想要忽略特定类型的警告,可以使用 `warnings` 的 `filterwarnings` 函数: -``` +```py filterwarnings(action, category) ``` @@ -44,7 +44,7 @@ filterwarnings(action, category) In [3]: -``` +```py warnings.filterwarnings(action = 'ignore', category = RuntimeWarning) month_warning(13) diff --git a/docs/da/027.md b/docs/da/027.md index 7941146be..ae961793c 100644 --- a/docs/da/027.md +++ b/docs/da/027.md @@ -4,7 +4,7 @@ In [1]: -``` +```py %%writefile test.txt this is a test file. hello world! @@ -13,7 +13,7 @@ today is a good day. ``` -``` +```py Writing test.txt ``` @@ -24,14 +24,14 @@ Writing test.txt In [2]: -``` +```py f = open('test.txt') ``` In [3]: -``` +```py f = file('test.txt') ``` @@ -44,13 +44,13 @@ f = file('test.txt') In [4]: -``` +```py text = f.read() print text ``` -``` +```py this is a test file. hello world! python is good! @@ -62,14 +62,14 @@ today is a good day. In [5]: -``` +```py f = open('test.txt') lines = f.readlines() print lines ``` -``` +```py ['this is a test file.\n', 'hello world!\n', 'python is good!\n', 'today is a good day.'] ``` @@ -78,7 +78,7 @@ print lines In [6]: -``` +```py f.close() ``` @@ -87,7 +87,7 @@ f.close() In [7]: -``` +```py f = open('test.txt') for line in f: print line @@ -95,7 +95,7 @@ f.close() ``` -``` +```py this is a test file. hello world! @@ -110,7 +110,7 @@ today is a good day. In [8]: -``` +```py import os os.remove('test.txt') @@ -122,7 +122,7 @@ os.remove('test.txt') In [9]: -``` +```py f = open('myfile.txt', 'w') f.write('hello world!') f.close() @@ -133,12 +133,12 @@ f.close() In [10]: -``` +```py print open('myfile.txt').read() ``` -``` +```py hello world! ``` @@ -147,7 +147,7 @@ hello world! In [11]: -``` +```py f = open('myfile.txt', 'w') f.write('another hello world!') f.close() @@ -155,7 +155,7 @@ print open('myfile.txt').read() ``` -``` +```py another hello world! ``` @@ -164,7 +164,7 @@ another hello world! In [12]: -``` +```py f = open('myfile.txt', 'a') f.write('... and more') f.close() @@ -172,7 +172,7 @@ print open('myfile.txt').read() ``` -``` +```py another hello world!... and more ``` @@ -183,7 +183,7 @@ another hello world!... and more In [13]: -``` +```py f = open('myfile.txt', 'w+') f.write('hello world!') f.seek(6) @@ -192,7 +192,7 @@ f.close() ``` -``` +```py world! ``` @@ -201,7 +201,7 @@ world! In [14]: -``` +```py import os os.remove('myfile.txt') @@ -213,7 +213,7 @@ os.remove('myfile.txt') In [15]: -``` +```py import os f = open('binary.bin', 'wb') f.write(os.urandom(16)) @@ -225,14 +225,14 @@ f.close() ``` -``` +```py '\x86H\x93\xe1\xd8\xef\xc0\xaa(\x17\xa9\xc9\xa51\xf1\x98' ``` In [16]: -``` +```py import os os.remove('binary.bin') @@ -258,7 +258,7 @@ os.remove('binary.bin') In [17]: -``` +```py f = open('newfile.txt','w') f.write('hello world') g = open('newfile.txt', 'r') @@ -266,7 +266,7 @@ print repr(g.read()) ``` -``` +```py '' ``` @@ -277,7 +277,7 @@ print repr(g.read()) In [18]: -``` +```py f = open('newfile.txt','w') for i in range(3000): f.write('hello world: ' + str(i) + '\n') @@ -289,7 +289,7 @@ g.close() ``` -``` +```py hello world: 0 hello world: 1 hello world: 2 @@ -3088,7 +3088,7 @@ hello In [19]: -``` +```py import os os.remove('newfile.txt') @@ -3098,7 +3098,7 @@ os.remove('newfile.txt') In [20]: -``` +```py f = open('newfile.txt','w') for i in range(3000): x = 1.0 / (i - 1000) @@ -3106,7 +3106,7 @@ for i in range(3000): ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -3122,7 +3122,7 @@ ZeroDivisionError: float division by zero In [21]: -``` +```py g = open('newfile.txt', 'r') print g.read() f.close() @@ -3130,7 +3130,7 @@ g.close() ``` -``` +```py hello world: 0 hello world: 1 hello world: 2 @@ -4109,7 +4109,7 @@ hell In [22]: -``` +```py f = open('newfile.txt','w') try: for i in range(3000): @@ -4122,21 +4122,21 @@ finally: ``` -``` +```py something bad happened ``` In [23]: -``` +```py g = open('newfile.txt', 'r') print g.read() g.close() ``` -``` +```py hello world: 0 hello world: 1 hello world: 2 @@ -5146,7 +5146,7 @@ hello world: 999 In [24]: -``` +```py with open('newfile.txt','w') as f: for i in range(3000): x = 1.0 / (i - 1000) @@ -5154,7 +5154,7 @@ with open('newfile.txt','w') as f: ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -5170,14 +5170,14 @@ ZeroDivisionError: float division by zero In [25]: -``` +```py g = open('newfile.txt', 'r') print g.read() g.close() ``` -``` +```py hello world: 0 hello world: 1 hello world: 2 @@ -6185,7 +6185,7 @@ hello world: 999 In [26]: -``` +```py import os os.remove('newfile.txt') diff --git a/docs/da/029.md b/docs/da/029.md index d2b45ed06..caf7ca731 100644 --- a/docs/da/029.md +++ b/docs/da/029.md @@ -10,14 +10,14 @@ In [1]: -``` +```py from numpy import * ``` 使用前一定要先导入 Numpy 包,导入的方法有以下几种: -``` +```py import numpy import numpy as np from numpy import * @@ -29,12 +29,12 @@ import numpy In [2]: -``` +```py %pylab ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -46,13 +46,13 @@ Populating the interactive namespace from numpy and matplotlib In [3]: -``` +```py a = [1, 2, 3, 4] a + 1 ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -66,7 +66,7 @@ TypeError: can only concatenate list (not "int") to list In [4]: -``` +```py a = array(a) a @@ -74,7 +74,7 @@ a Out[4]: -``` +```py array([1, 2, 3, 4]) ``` @@ -82,14 +82,14 @@ array([1, 2, 3, 4]) In [5]: -``` +```py a + 1 ``` Out[5]: -``` +```py array([2, 3, 4, 5]) ``` @@ -97,7 +97,7 @@ array([2, 3, 4, 5]) In [6]: -``` +```py b = array([2, 3, 4, 5]) a + b @@ -105,7 +105,7 @@ a + b Out[6]: -``` +```py array([3, 5, 7, 9]) ``` @@ -113,14 +113,14 @@ array([3, 5, 7, 9]) In [7]: -``` +```py a * b ``` Out[7]: -``` +```py array([ 2, 6, 12, 20]) ``` @@ -128,14 +128,14 @@ array([ 2, 6, 12, 20]) In [8]: -``` +```py a ** b ``` Out[8]: -``` +```py array([ 1, 8, 81, 1024]) ``` @@ -145,14 +145,14 @@ array([ 1, 8, 81, 1024]) In [9]: -``` +```py a[0] ``` Out[9]: -``` +```py 1 ``` @@ -160,14 +160,14 @@ Out[9]: In [10]: -``` +```py a[:2] ``` Out[10]: -``` +```py array([1, 2]) ``` @@ -175,14 +175,14 @@ array([1, 2]) In [11]: -``` +```py a[-2:] ``` Out[11]: -``` +```py array([3, 4]) ``` @@ -190,14 +190,14 @@ array([3, 4]) In [12]: -``` +```py a[:2] + a[-2:] ``` Out[12]: -``` +```py array([4, 6]) ``` @@ -207,14 +207,14 @@ array([4, 6]) In [13]: -``` +```py a.shape ``` Out[13]: -``` +```py (4L,) ``` @@ -222,7 +222,7 @@ Out[13]: In [14]: -``` +```py a.shape = 2,2 a @@ -230,7 +230,7 @@ a Out[14]: -``` +```py array([[1, 2], [3, 4]]) ``` @@ -241,14 +241,14 @@ array([[1, 2], In [15]: -``` +```py a + a ``` Out[15]: -``` +```py array([[2, 4], [6, 8]]) ``` @@ -257,14 +257,14 @@ array([[2, 4], In [16]: -``` +```py a * a ``` Out[16]: -``` +```py array([[ 1, 4], [ 9, 16]]) ``` @@ -275,7 +275,7 @@ linspace 用来生成一组等间隔的数据: In [17]: -``` +```py a = linspace(0, 2*pi, 21) %precision 3 a @@ -284,7 +284,7 @@ a Out[17]: -``` +```py array([ 0\. , 0.314, 0.628, 0.942, 1.257, 1.571, 1.885, 2.199, 2.513, 2.827, 3.142, 3.456, 3.77 , 4.084, 4.398, 4.712, 5.027, 5.341, 5.655, 5.969, 6.283]) @@ -294,7 +294,7 @@ array([ 0\. , 0.314, 0.628, 0.942, 1.257, 1.571, 1.885, 2.199, In [18]: -``` +```py b = sin(a) b @@ -302,7 +302,7 @@ b Out[18]: -``` +```py array([ 0.000e+00, 3.090e-01, 5.878e-01, 8.090e-01, 9.511e-01, 1.000e+00, 9.511e-01, 8.090e-01, 5.878e-01, 3.090e-01, 1.225e-16, -3.090e-01, -5.878e-01, -8.090e-01, -9.511e-01, @@ -314,7 +314,7 @@ array([ 0.000e+00, 3.090e-01, 5.878e-01, 8.090e-01, 9.511e-01, In [19]: -``` +```py %matplotlib inline plot(a, b) @@ -322,7 +322,7 @@ plot(a, b) Out[19]: -``` +```py [] ``` @@ -490,14 +490,14 @@ HzC+mVy4trE1AAAAAElFTkSuQmCC In [20]: -``` +```py b >= 0 ``` Out[20]: -``` +```py array([ True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False], dtype=bool) @@ -505,7 +505,7 @@ array([ True, True, True, True, True, True, True, True, True, In [21]: -``` +```py mask = b >= 0 ``` @@ -514,14 +514,14 @@ mask = b >= 0 In [22]: -``` +```py plot(a[mask], b[mask], 'ro') ``` Out[22]: -``` +```py [] ``` diff --git a/docs/da/030.md b/docs/da/030.md index c2bb16f84..672cde2e7 100644 --- a/docs/da/030.md +++ b/docs/da/030.md @@ -10,12 +10,12 @@ In [1]: -``` +```py %pylab ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -23,7 +23,7 @@ Populating the interactive namespace from numpy and matplotlib ## plot 二维图 -``` +```py plot(y) plot(x, y) plot(x, y, format_string) @@ -34,7 +34,7 @@ plot(x, y, format_string) In [2]: -``` +```py %matplotlib inline x = linspace(0, 2 * pi, 50) plot(sin(x)) @@ -43,7 +43,7 @@ plot(sin(x)) Out[2]: -``` +```py [] ``` @@ -208,14 +208,14 @@ RUQiRElfRCRClPRFRCJESV9EJEKU9EVEIuT/A6BIi/UzzUVtAAAAAElFTkSuQmCC In [3]: -``` +```py plot(x, sin(x)) ``` Out[3]: -``` +```py [] ``` @@ -381,7 +381,7 @@ gg== In [4]: -``` +```py plot(x, sin(x), x, sin(2 * x)) @@ -389,7 +389,7 @@ plot(x, sin(x), Out[4]: -``` +```py [, ] ``` @@ -705,14 +705,14 @@ KBQKN+f/AQEk9vM2SbiHAAAAAElFTkSuQmCC In [5]: -``` +```py plot(x, sin(x), 'r-^') ``` Out[5]: -``` +```py [] ``` @@ -896,7 +896,7 @@ SvQiIhlOiV5EJMMp0YuIZDglehGRDKdELyKS4f4/AlyjccYZ7k4AAAAASUVORK5CYII= In [9]: -``` +```py plot(x, sin(x), 'b-o', x, sin(2 * x), 'r-^') @@ -904,7 +904,7 @@ plot(x, sin(x), 'b-o', Out[9]: -``` +```py [, ] ``` @@ -1231,7 +1231,7 @@ Duf/AbP7N0Qt3HMbAAAAAElFTkSuQmCC ## scatter 散点图 -``` +```py scatter(x, y) scatter(x, y, size) scatter(x, y, size, color) @@ -1242,14 +1242,14 @@ scatter(x, y, size, color) In [10]: -``` +```py plot(x, sin(x), 'bo') ``` Out[10]: -``` +```py [] ``` @@ -1352,14 +1352,14 @@ bKpvNy2mHwAAAABJRU5ErkJggg== In [11]: -``` +```py scatter(x, sin(x)) ``` Out[11]: -``` +```py ``` @@ -1462,7 +1462,7 @@ CHoASBxBDwCJI+gBIHEEPQAkjqAHgMT9P+IRy0P0DiDZAAAAAElFTkSuQmCC In [12]: -``` +```py x = rand(200) y = rand(200) size = rand(200) * 30 @@ -1475,7 +1475,7 @@ colorbar() Out[12]: -``` +```py ``` @@ -2004,7 +2004,7 @@ DQ0H4P8DJu8dXcDMQQAAAABJRU5ErkJggg== In [13]: -``` +```py t = linspace(0, 2*pi, 50) x = sin(t) y = cos(t) @@ -2017,7 +2017,7 @@ plot(y) Out[13]: -``` +```py [] ``` @@ -2335,13 +2335,13 @@ ERV9EZEY+X9EO9oF1xEZ7QAAAABJRU5ErkJggg== 或者使用 `subplot` 在一幅图中画多幅子图: -``` +```py subplot(row, column, index) ``` In [15]: -``` +```py subplot(1, 2, 1) plot(x) subplot(1, 2, 2) @@ -2351,7 +2351,7 @@ plot(y) Out[15]: -``` +```py [] ``` @@ -2551,7 +2551,7 @@ MI+06AAAAABJRU5ErkJggg== In [16]: -``` +```py plot(x) plot(y) @@ -2559,7 +2559,7 @@ plot(y) Out[16]: -``` +```py [] ``` @@ -2841,7 +2841,7 @@ ir5hGIYH+R9/BjfcPdcAvwAAAABJRU5ErkJggg== In [17]: -``` +```py plot(x) hold(False) plot(y) @@ -2852,7 +2852,7 @@ hold(True) Out[17]: -``` +```py [] ``` @@ -3019,7 +3019,7 @@ ERV9EZEY+X9EO9oF1xEZ7QAAAABJRU5ErkJggg== In [19]: -``` +```py plot(x, label='sin') plot(y, label='cos') legend() @@ -3028,7 +3028,7 @@ legend() Out[19]: -``` +```py ``` @@ -3312,7 +3312,7 @@ YXgQU/QNwzA8iCn6hmEYHuT/Hiuv2gfQi84AAAAASUVORK5CYII= In [21]: -``` +```py plot(x) plot(y) legend(['sin', 'cos']) @@ -3321,7 +3321,7 @@ legend(['sin', 'cos']) Out[21]: -``` +```py ``` @@ -3607,7 +3607,7 @@ YXgQU/QNwzA8iCn6hmEYHuT/Hiuv2gfQi84AAAAASUVORK5CYII= In [22]: -``` +```py plot(x, sin(x)) xlabel('radians') # 可以设置字体大小 @@ -3618,7 +3618,7 @@ title('Sin(x)') Out[22]: -``` +```py ``` @@ -3781,7 +3781,7 @@ QmCC In [23]: -``` +```py plot(x, sin(x)) xlabel('radians') ylabel('amplitude', fontsize='large') @@ -3961,19 +3961,19 @@ iIiI5EUJRERE8qIEIiIieVECERGRvPwfMOmeP1xnpUIAAAAASUVORK5CYII= 清除已有的图像使用: -``` +```py clf() ``` 关闭当前图像: -``` +```py close() ``` 关闭所有图像: -``` +```py close('all') ``` @@ -3983,7 +3983,7 @@ close('all') In [25]: -``` +```py # 导入lena图片 from scipy.misc import lena img = lena() @@ -3993,7 +3993,7 @@ img Out[25]: -``` +```py array([[162, 162, 162, ..., 170, 155, 128], [162, 162, 162, ..., 170, 155, 128], [162, 162, 162, ..., 170, 155, 128], @@ -4007,7 +4007,7 @@ array([[162, 162, 162, ..., 170, 155, 128], In [26]: -``` +```py imshow(img, # 设置坐标范围 extent = [-25, 25, -25, 25], @@ -4019,7 +4019,7 @@ colorbar() Out[26]: -``` +```py ``` @@ -5886,14 +5886,14 @@ yJFj2yFPbDly5Nh2yBNbjhw5th3yxJYjR45thzyx5ciRY9vh3x6l2ExxWzdiAAAAAElFTkSuQmCC In [28]: -``` +```py dir(cm) ``` Out[28]: -``` +```py [u'Accent', u'Accent_r', u'Blues', @@ -6073,14 +6073,14 @@ Out[28]: In [29]: -``` +```py imshow(img, cmap=cm.RdGy_r) ``` Out[29]: -``` +```py ``` @@ -7957,14 +7957,14 @@ SUVORK5CYII= In [30]: -``` +```py hist(randn(1000)) ``` Out[30]: -``` +```py (array([ 2., 7., 37., 119., 216., 270., 223., 82., 31., 13.]), array([-3.65594649, -2.98847032, -2.32099415, -1.65351798, -0.98604181, -0.31856564, 0.34891053, 1.0163867 , 1.68386287, 2.35133904, diff --git a/docs/da/031.md b/docs/da/031.md index d3f07d97c..a426e46c3 100644 --- a/docs/da/031.md +++ b/docs/da/031.md @@ -4,7 +4,7 @@ In [1]: -``` +```py from numpy import * ``` @@ -15,7 +15,7 @@ from numpy import * In [2]: -``` +```py lst = [0, 1, 2, 3] a = array(lst) a @@ -24,7 +24,7 @@ a Out[2]: -``` +```py array([0, 1, 2, 3]) ``` @@ -32,7 +32,7 @@ array([0, 1, 2, 3]) In [3]: -``` +```py a = array([1, 2, 3, 4]) a @@ -40,7 +40,7 @@ a Out[3]: -``` +```py array([1, 2, 3, 4]) ``` @@ -50,14 +50,14 @@ array([1, 2, 3, 4]) In [4]: -``` +```py type(a) ``` Out[4]: -``` +```py numpy.ndarray ``` @@ -65,7 +65,7 @@ numpy.ndarray In [5]: -``` +```py # 32比特的整数 a.dtype @@ -73,7 +73,7 @@ a.dtype Out[5]: -``` +```py dtype('int32') ``` @@ -81,14 +81,14 @@ dtype('int32') In [6]: -``` +```py a.itemsize ``` Out[6]: -``` +```py 4 ``` @@ -96,7 +96,7 @@ Out[6]: In [7]: -``` +```py # 1维数组,返回一个元组 a.shape @@ -104,7 +104,7 @@ a.shape Out[7]: -``` +```py (4L,) ``` @@ -112,14 +112,14 @@ Out[7]: In [8]: -``` +```py shape(a) ``` Out[8]: -``` +```py (4L,) ``` @@ -127,7 +127,7 @@ Out[8]: In [9]: -``` +```py lst = [1,2,3,4] shape(lst) @@ -135,7 +135,7 @@ shape(lst) Out[9]: -``` +```py (4L,) ``` @@ -143,27 +143,27 @@ Out[9]: In [10]: -``` +```py a.size ``` Out[10]: -``` +```py 4 ``` In [11]: -``` +```py size(a) ``` Out[11]: -``` +```py 4 ``` @@ -171,14 +171,14 @@ Out[11]: In [12]: -``` +```py a.nbytes ``` Out[12]: -``` +```py 16 ``` @@ -188,14 +188,14 @@ Out[12]: In [13]: -``` +```py a.ndim ``` Out[13]: -``` +```py 1 ``` @@ -205,7 +205,7 @@ Out[13]: In [14]: -``` +```py a.fill(-4.8) a @@ -213,7 +213,7 @@ a Out[14]: -``` +```py array([-4, -4, -4, -4]) ``` @@ -227,7 +227,7 @@ array([-4, -4, -4, -4]) In [15]: -``` +```py a = array([0, 1, 2, 3]) a[0] @@ -235,7 +235,7 @@ a[0] Out[15]: -``` +```py 0 ``` @@ -243,7 +243,7 @@ Out[15]: In [16]: -``` +```py a[0] = 10 a @@ -251,7 +251,7 @@ a Out[16]: -``` +```py array([10, 1, 2, 3]) ``` @@ -259,7 +259,7 @@ array([10, 1, 2, 3]) In [17]: -``` +```py a = array([11,12,13,14,15]) a[1:3] @@ -267,33 +267,33 @@ a[1:3] Out[17]: -``` +```py array([12, 13]) ``` In [18]: -``` +```py a[1:-2] ``` Out[18]: -``` +```py array([12, 13]) ``` In [19]: -``` +```py a[-4:3] ``` Out[19]: -``` +```py array([12, 13]) ``` @@ -301,27 +301,27 @@ array([12, 13]) In [20]: -``` +```py a[::2] ``` Out[20]: -``` +```py array([11, 13, 15]) ``` In [21]: -``` +```py a[-2:] ``` Out[21]: -``` +```py array([14, 15]) ``` @@ -329,7 +329,7 @@ array([14, 15]) In [22]: -``` +```py od = array([21000, 21180, 21240, 22100, 22400]) ``` @@ -338,7 +338,7 @@ od = array([21000, 21180, 21240, 22100, 22400]) In [23]: -``` +```py dist = od[1:] - od[:-1] dist @@ -346,13 +346,13 @@ dist Out[23]: -``` +```py array([180, 60, 860, 300]) ``` 在本质上,**Python**会将array的各种计算转换为类似这样的**C**代码: -``` +```py int compute_sum(int *arr, int N) { int sum = 0; int i; @@ -370,7 +370,7 @@ int compute_sum(int *arr, int N) { In [24]: -``` +```py a = array([[ 0, 1, 2, 3], [10,11,12,13]]) a @@ -379,7 +379,7 @@ a Out[24]: -``` +```py array([[ 0, 1, 2, 3], [10, 11, 12, 13]]) ``` @@ -392,14 +392,14 @@ array([[ 0, 1, 2, 3], In [25]: -``` +```py a.shape ``` Out[25]: -``` +```py (2L, 4L) ``` @@ -409,7 +409,7 @@ Out[25]: In [26]: -``` +```py # 2 * 4 = 8 a.size @@ -417,7 +417,7 @@ a.size Out[26]: -``` +```py 8 ``` @@ -425,14 +425,14 @@ Out[26]: In [27]: -``` +```py a.ndim ``` Out[27]: -``` +```py 2 ``` @@ -442,14 +442,14 @@ Out[27]: In [28]: -``` +```py a[1, 3] ``` Out[28]: -``` +```py 13 ``` @@ -459,7 +459,7 @@ Out[28]: In [29]: -``` +```py a[1, 3] = -1 a @@ -467,7 +467,7 @@ a Out[29]: -``` +```py array([[ 0, 1, 2, 3], [10, 11, 12, -1]]) ``` @@ -476,7 +476,7 @@ array([[ 0, 1, 2, 3], In [30]: -``` +```py # 返回第二行元组组成的array a[1] @@ -484,7 +484,7 @@ a[1] Out[30]: -``` +```py array([10, 11, 12, -1]) ``` @@ -496,7 +496,7 @@ array([10, 11, 12, -1]) In [31]: -``` +```py a = array([[ 0, 1, 2, 3, 4, 5], [10,11,12,13,14,15], [20,21,22,23,24,25], @@ -509,7 +509,7 @@ a Out[31]: -``` +```py array([[ 0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25], @@ -522,14 +522,14 @@ array([[ 0, 1, 2, 3, 4, 5], In [32]: -``` +```py a[0, 3:5] ``` Out[32]: -``` +```py array([3, 4]) ``` @@ -537,14 +537,14 @@ array([3, 4]) In [33]: -``` +```py a[4:, 4:] ``` Out[33]: -``` +```py array([[44, 45], [54, 55]]) ``` @@ -553,20 +553,20 @@ array([[44, 45], In [34]: -``` +```py a[:, 2] ``` Out[34]: -``` +```py array([ 2, 12, 22, 32, 42, 52]) ``` 每一维都支持切片的规则,包括负索引,省略: -``` +```py [lower:upper:step] ``` @@ -574,14 +574,14 @@ array([ 2, 12, 22, 32, 42, 52]) In [35]: -``` +```py a[2::2, ::2] ``` Out[35]: -``` +```py array([[20, 22, 24], [40, 42, 44]]) ``` @@ -592,14 +592,14 @@ array([[20, 22, 24], In [36]: -``` +```py a = array([0,1,2,3,4]) b = a[2:4] print b ``` -``` +```py [2 3] ``` @@ -608,7 +608,7 @@ print b In [37]: -``` +```py b[0] = 10 a @@ -616,7 +616,7 @@ a Out[37]: -``` +```py array([ 0, 1, 10, 3, 4]) ``` @@ -624,7 +624,7 @@ array([ 0, 1, 10, 3, 4]) In [38]: -``` +```py a = [1,2,3,4,5] b = a[2:3] b[0] = 13234 @@ -632,7 +632,7 @@ print a ``` -``` +```py [1, 2, 3, 4, 5] ``` @@ -645,7 +645,7 @@ print a In [39]: -``` +```py a = array([0,1,2,3,4]) b = a[2:4].copy() b[0] = 10 @@ -655,7 +655,7 @@ a Out[39]: -``` +```py array([0, 1, 2, 3, 4]) ``` @@ -669,7 +669,7 @@ array([0, 1, 2, 3, 4]) In [40]: -``` +```py a = arange(0, 80, 10) a @@ -677,7 +677,7 @@ a Out[40]: -``` +```py array([ 0, 10, 20, 30, 40, 50, 60, 70]) ``` @@ -685,14 +685,14 @@ array([ 0, 10, 20, 30, 40, 50, 60, 70]) In [41]: -``` +```py indices = [1, 2, -3] y = a[indices] print y ``` -``` +```py [10 20 50] ``` @@ -701,7 +701,7 @@ print y In [42]: -``` +```py mask = array([0,1,1,0,0,1,0,0], dtype=bool) @@ -709,14 +709,14 @@ mask = array([0,1,1,0,0,1,0,0], In [43]: -``` +```py a[mask] ``` Out[43]: -``` +```py array([10, 20, 50]) ``` @@ -724,7 +724,7 @@ array([10, 20, 50]) In [44]: -``` +```py from numpy.random import rand a = rand(10) a @@ -733,14 +733,14 @@ a Out[44]: -``` +```py array([ 0.37214708, 0.48594733, 0.73365131, 0.15769295, 0.30786017, 0.62068734, 0.36940654, 0.09424167, 0.53085308, 0.12248951]) ``` In [45]: -``` +```py mask = a > 0.5 a[mask] @@ -748,7 +748,7 @@ a[mask] Out[45]: -``` +```py array([ 0.73365131, 0.62068734, 0.53085308]) ``` @@ -758,7 +758,7 @@ mask 必须是布尔数组。 In [46]: -``` +```py a = array([[ 0, 1, 2, 3, 4, 5], [10,11,12,13,14,15], [20,21,22,23,24,25], @@ -771,7 +771,7 @@ a Out[46]: -``` +```py array([[ 0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25], @@ -784,14 +784,14 @@ array([[ 0, 1, 2, 3, 4, 5], In [47]: -``` +```py a[(0,1,2,3,4), (1,2,3,4,5)] ``` Out[47]: -``` +```py array([ 1, 12, 23, 34, 45]) ``` @@ -799,14 +799,14 @@ array([ 1, 12, 23, 34, 45]) In [48]: -``` +```py a[3:, [0,2,5]] ``` Out[48]: -``` +```py array([[30, 32, 35], [40, 42, 45], [50, 52, 55]]) @@ -818,7 +818,7 @@ array([[30, 32, 35], In [49]: -``` +```py mask = array([1,0,1,0,0,1], dtype=bool) a[mask, 2] @@ -827,7 +827,7 @@ a[mask, 2] Out[49]: -``` +```py array([ 2, 22, 52]) ``` @@ -839,7 +839,7 @@ array([ 2, 22, 52]) In [50]: -``` +```py y = a[:3] y @@ -847,7 +847,7 @@ y Out[50]: -``` +```py array([[ 0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25]]) @@ -857,7 +857,7 @@ array([[ 0, 1, 2, 3, 4, 5], In [51]: -``` +```py condition = array([0,1,1,0,1], dtype=bool) a[condition] @@ -866,7 +866,7 @@ a[condition] Out[51]: -``` +```py array([[10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25], [40, 41, 42, 43, 44, 45]]) @@ -876,7 +876,7 @@ array([[10, 11, 12, 13, 14, 15], In [52]: -``` +```py a = arange(64) a.shape = 4,4,4 a @@ -885,7 +885,7 @@ a Out[52]: -``` +```py array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], @@ -909,7 +909,7 @@ array([[[ 0, 1, 2, 3], In [53]: -``` +```py y = a[:,:,[2, -1]] y @@ -917,7 +917,7 @@ y Out[53]: -``` +```py array([[[ 2, 3], [ 6, 7], [10, 11], @@ -941,7 +941,7 @@ array([[[ 2, 3], ## where语句 -``` +```py where(array) ``` @@ -953,7 +953,7 @@ where(array) In [54]: -``` +```py a = array([0, 12, 5, 20]) ``` @@ -962,14 +962,14 @@ a = array([0, 12, 5, 20]) In [55]: -``` +```py a > 10 ``` Out[55]: -``` +```py array([False, True, False, True], dtype=bool) ``` @@ -977,14 +977,14 @@ array([False, True, False, True], dtype=bool) In [56]: -``` +```py where(a > 10) ``` Out[56]: -``` +```py (array([1, 3], dtype=int64),) ``` @@ -996,7 +996,7 @@ Out[56]: In [57]: -``` +```py indices = where(a > 10) indices = indices[0] indices @@ -1005,7 +1005,7 @@ indices Out[57]: -``` +```py array([1, 3], dtype=int64) ``` @@ -1013,7 +1013,7 @@ array([1, 3], dtype=int64) In [58]: -``` +```py indices = where(a>10)[0] indices @@ -1021,7 +1021,7 @@ indices Out[58]: -``` +```py array([1, 3], dtype=int64) ``` @@ -1029,7 +1029,7 @@ array([1, 3], dtype=int64) In [59]: -``` +```py loc = where(a > 10) a[loc] @@ -1037,7 +1037,7 @@ a[loc] Out[59]: -``` +```py array([12, 20]) ``` @@ -1047,7 +1047,7 @@ array([12, 20]) In [60]: -``` +```py a = array([[0, 12, 5, 20], [1, 2, 11, 15]]) loc = where(a > 10) @@ -1058,14 +1058,14 @@ loc = where(a > 10) In [61]: -``` +```py loc ``` Out[61]: -``` +```py (array([0, 0, 1, 1], dtype=int64), array([1, 3, 2, 3], dtype=int64)) ``` @@ -1073,14 +1073,14 @@ Out[61]: In [62]: -``` +```py a[loc] ``` Out[62]: -``` +```py array([12, 20, 11, 15]) ``` @@ -1088,47 +1088,47 @@ array([12, 20, 11, 15]) In [63]: -``` +```py rows, cols = where(a>10) ``` In [64]: -``` +```py rows ``` Out[64]: -``` +```py array([0, 0, 1, 1], dtype=int64) ``` In [65]: -``` +```py cols ``` Out[65]: -``` +```py array([1, 3, 2, 3], dtype=int64) ``` In [66]: -``` +```py a[rows, cols] ``` Out[66]: -``` +```py array([12, 20, 11, 15]) ``` @@ -1136,7 +1136,7 @@ array([12, 20, 11, 15]) In [67]: -``` +```py a = arange(25) a.shape = 5,5 a @@ -1145,7 +1145,7 @@ a Out[67]: -``` +```py array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], @@ -1155,14 +1155,14 @@ array([[ 0, 1, 2, 3, 4], In [68]: -``` +```py a > 12 ``` Out[68]: -``` +```py array([[False, False, False, False, False], [False, False, False, False, False], [False, False, False, True, True], @@ -1172,14 +1172,14 @@ array([[False, False, False, False, False], In [69]: -``` +```py where(a > 12) ``` Out[69]: -``` +```py (array([2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4], dtype=int64), array([3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64)) ``` \ No newline at end of file diff --git a/docs/da/032.md b/docs/da/032.md index 0a57b4d98..016acd9b0 100644 --- a/docs/da/032.md +++ b/docs/da/032.md @@ -2,7 +2,7 @@ In [1]: -``` +```py from numpy import * ``` @@ -15,7 +15,7 @@ from numpy import * In [2]: -``` +```py a = array([1 + 1j, 2, 3, 4]) ``` @@ -24,14 +24,14 @@ a = array([1 + 1j, 2, 3, 4]) In [3]: -``` +```py a.dtype ``` Out[3]: -``` +```py dtype('complex128') ``` @@ -39,27 +39,27 @@ dtype('complex128') In [4]: -``` +```py a.real ``` Out[4]: -``` +```py array([ 1., 2., 3., 4.]) ``` In [5]: -``` +```py a.imag ``` Out[5]: -``` +```py array([ 1., 0., 0., 0.]) ``` @@ -67,7 +67,7 @@ array([ 1., 0., 0., 0.]) In [6]: -``` +```py a.imag = [1,2,3,4] ``` @@ -76,14 +76,14 @@ a.imag = [1,2,3,4] In [7]: -``` +```py a ``` Out[7]: -``` +```py array([ 1.+1.j, 2.+2.j, 3.+3.j, 4.+4.j]) ``` @@ -91,14 +91,14 @@ array([ 1.+1.j, 2.+2.j, 3.+3.j, 4.+4.j]) In [8]: -``` +```py a.conj() ``` Out[8]: -``` +```py array([ 1.-1.j, 2.-2.j, 3.-3.j, 4.-4.j]) ``` @@ -106,7 +106,7 @@ array([ 1.-1.j, 2.-2.j, 3.-3.j, 4.-4.j]) In [9]: -``` +```py a = array([0.,1,2,3]) a.dtype @@ -114,46 +114,46 @@ a.dtype Out[9]: -``` +```py dtype('float64') ``` In [10]: -``` +```py a.real ``` Out[10]: -``` +```py array([ 0., 1., 2., 3.]) ``` In [11]: -``` +```py a.imag ``` Out[11]: -``` +```py array([ 0., 0., 0., 0.]) ``` In [12]: -``` +```py a.conj() ``` Out[12]: -``` +```py array([ 0., 1., 2., 3.]) ``` @@ -161,13 +161,13 @@ array([ 0., 1., 2., 3.]) In [13]: -``` +```py # 会报错 a.imag = [1,2,3,4] ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -183,7 +183,7 @@ TypeError: array does not have imaginary part to set In [14]: -``` +```py a = array([0,1.0,2,3]) ``` @@ -192,14 +192,14 @@ a = array([0,1.0,2,3]) In [15]: -``` +```py a.dtype ``` Out[15]: -``` +```py dtype('float64') ``` @@ -207,14 +207,14 @@ dtype('float64') In [16]: -``` +```py a.nbytes ``` Out[16]: -``` +```py 32 ``` @@ -222,7 +222,7 @@ Out[16]: In [17]: -``` +```py a = array([0,1.0,2,3], dtype=float32) @@ -232,14 +232,14 @@ a = array([0,1.0,2,3], In [18]: -``` +```py a.dtype ``` Out[18]: -``` +```py dtype('float32') ``` @@ -247,14 +247,14 @@ dtype('float32') In [19]: -``` +```py a.nbytes ``` Out[19]: -``` +```py 16 ``` @@ -262,7 +262,7 @@ Out[19]: In [20]: -``` +```py a = array([0,1,2,3], dtype=uint8) a.dtype @@ -271,7 +271,7 @@ a.dtype Out[20]: -``` +```py dtype('uint8') ``` @@ -283,7 +283,7 @@ dtype('uint8') In [21]: -``` +```py a = array([102,111,212], dtype=uint8) a.tofile('foo.dat') @@ -294,7 +294,7 @@ a.tofile('foo.dat') In [22]: -``` +```py b = frombuffer('foo', dtype=uint8) b @@ -303,7 +303,7 @@ b Out[22]: -``` +```py array([102, 111, 111], dtype=uint8) ``` @@ -311,7 +311,7 @@ array([102, 111, 111], dtype=uint8) In [23]: -``` +```py import os os.remove('foo.dat') @@ -321,27 +321,27 @@ os.remove('foo.dat') In [24]: -``` +```py ord('f') ``` Out[24]: -``` +```py 102 ``` In [25]: -``` +```py ord('S') ``` Out[25]: -``` +```py 83 ``` @@ -365,7 +365,7 @@ Out[25]: In [26]: -``` +```py a = array([1,1.2,'hello', [10,20,30]], dtype=object) @@ -375,14 +375,14 @@ a = array([1,1.2,'hello', [10,20,30]], In [27]: -``` +```py a * 2 ``` Out[27]: -``` +```py array([2, 2.4, 'hellohello', [10, 20, 30, 10, 20, 30]], dtype=object) ``` @@ -392,7 +392,7 @@ array([2, 2.4, 'hellohello', [10, 20, 30, 10, 20, 30]], dtype=object) In [28]: -``` +```py a = array([1.5, -3], dtype=float32) a @@ -401,7 +401,7 @@ a Out[28]: -``` +```py array([ 1.5, -3\. ], dtype=float32) ``` @@ -411,27 +411,27 @@ array([ 1.5, -3\. ], dtype=float32) In [29]: -``` +```py asarray(a, dtype=float64) ``` Out[29]: -``` +```py array([ 1.5, -3\. ]) ``` In [30]: -``` +```py asarray(a, dtype=uint8) ``` Out[30]: -``` +```py array([ 1, 253], dtype=uint8) ``` @@ -439,14 +439,14 @@ array([ 1, 253], dtype=uint8) In [31]: -``` +```py a ``` Out[31]: -``` +```py array([ 1.5, -3\. ], dtype=float32) ``` @@ -454,21 +454,21 @@ array([ 1.5, -3\. ], dtype=float32) In [32]: -``` +```py b = asarray(a, dtype=float32) ``` In [33]: -``` +```py b is a ``` Out[33]: -``` +```py True ``` @@ -478,14 +478,14 @@ True In [34]: -``` +```py asarray([1,2,3,4]) ``` Out[34]: -``` +```py array([1, 2, 3, 4]) ``` @@ -495,27 +495,27 @@ array([1, 2, 3, 4]) In [35]: -``` +```py a.astype(float64) ``` Out[35]: -``` +```py array([ 1.5, -3\. ]) ``` In [36]: -``` +```py a.astype(uint8) ``` Out[36]: -``` +```py array([ 1, 253], dtype=uint8) ``` @@ -523,14 +523,14 @@ astype也不会改变原来数组的值: In [37]: -``` +```py a ``` Out[37]: -``` +```py array([ 1.5, -3\. ], dtype=float32) ``` @@ -538,14 +538,14 @@ array([ 1.5, -3\. ], dtype=float32) In [38]: -``` +```py b = a.astype(float32) print a print b ``` -``` +```py [ 1.5 -3\. ] [ 1.5 -3\. ] @@ -553,14 +553,14 @@ print b In [39]: -``` +```py a is b ``` Out[39]: -``` +```py False ``` @@ -568,7 +568,7 @@ False In [40]: -``` +```py a = array((1,2,3,4), dtype=int32) a @@ -576,7 +576,7 @@ a Out[40]: -``` +```py array([1, 2, 3, 4]) ``` @@ -584,7 +584,7 @@ array([1, 2, 3, 4]) In [41]: -``` +```py b = a.view(uint8) b @@ -592,13 +592,13 @@ b Out[41]: -``` +```py array([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0], dtype=uint8) ``` In [42]: -``` +```py a[0] = 2**30 a @@ -606,7 +606,7 @@ a Out[42]: -``` +```py array([1073741824, 2, 3, 4]) ``` @@ -614,13 +614,13 @@ array([1073741824, 2, 3, 4]) In [43]: -``` +```py b ``` Out[43]: -``` +```py array([ 0, 0, 0, 64, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0], dtype=uint8) ``` \ No newline at end of file diff --git a/docs/da/033.md b/docs/da/033.md index c211169c5..7b847bd5c 100644 --- a/docs/da/033.md +++ b/docs/da/033.md @@ -2,12 +2,12 @@ In [1]: -``` +```py %pylab ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -17,7 +17,7 @@ Populating the interactive namespace from numpy and matplotlib In [2]: -``` +```py a = array([[1,2,3], [4,5,6]]) @@ -27,14 +27,14 @@ a = array([[1,2,3], In [3]: -``` +```py sum(a) ``` Out[3]: -``` +```py 21 ``` @@ -44,14 +44,14 @@ Out[3]: In [4]: -``` +```py sum(a, axis=0) ``` Out[4]: -``` +```py array([5, 7, 9]) ``` @@ -59,14 +59,14 @@ array([5, 7, 9]) In [5]: -``` +```py sum(a, axis=1) ``` Out[5]: -``` +```py array([ 6, 15]) ``` @@ -74,14 +74,14 @@ array([ 6, 15]) In [6]: -``` +```py sum(a, axis=-1) ``` Out[6]: -``` +```py array([ 6, 15]) ``` @@ -89,40 +89,40 @@ array([ 6, 15]) In [7]: -``` +```py a.sum() ``` Out[7]: -``` +```py 21 ``` In [8]: -``` +```py a.sum(axis=0) ``` Out[8]: -``` +```py array([5, 7, 9]) ``` In [9]: -``` +```py a.sum(axis=-1) ``` Out[9]: -``` +```py array([ 6, 15]) ``` @@ -132,14 +132,14 @@ array([ 6, 15]) In [10]: -``` +```py a.prod() ``` Out[10]: -``` +```py 720 ``` @@ -147,14 +147,14 @@ Out[10]: In [11]: -``` +```py prod(a, axis=0) ``` Out[11]: -``` +```py array([ 4, 10, 18]) ``` @@ -162,7 +162,7 @@ array([ 4, 10, 18]) In [12]: -``` +```py from numpy.random import rand a = rand(3, 4) %precision 3 @@ -172,7 +172,7 @@ a Out[12]: -``` +```py array([[ 0.444, 0.06 , 0.668, 0.02 ], [ 0.793, 0.302, 0.81 , 0.381], [ 0.296, 0.182, 0.345, 0.686]]) @@ -182,14 +182,14 @@ array([[ 0.444, 0.06 , 0.668, 0.02 ], In [13]: -``` +```py a.min() ``` Out[13]: -``` +```py 0.020 ``` @@ -197,14 +197,14 @@ Out[13]: In [14]: -``` +```py a.min(axis=0) ``` Out[14]: -``` +```py array([ 0.296, 0.06 , 0.345, 0.02 ]) ``` @@ -212,14 +212,14 @@ array([ 0.296, 0.06 , 0.345, 0.02 ]) In [15]: -``` +```py a.max() ``` Out[15]: -``` +```py 0.810 ``` @@ -227,14 +227,14 @@ Out[15]: In [16]: -``` +```py a.max(axis=-1) ``` Out[16]: -``` +```py array([ 0.668, 0.81 , 0.686]) ``` @@ -244,27 +244,27 @@ array([ 0.668, 0.81 , 0.686]) In [17]: -``` +```py a.argmin() ``` Out[17]: -``` +```py 3 ``` In [18]: -``` +```py a.argmin(axis=0) ``` Out[18]: -``` +```py array([2, 0, 2, 0], dtype=int64) ``` @@ -274,34 +274,34 @@ array([2, 0, 2, 0], dtype=int64) In [19]: -``` +```py a = array([[1,2,3],[4,5,6]]) ``` In [20]: -``` +```py a.mean() ``` Out[20]: -``` +```py 3.500 ``` In [21]: -``` +```py a.mean(axis=-1) ``` Out[21]: -``` +```py array([ 2., 5.]) ``` @@ -309,14 +309,14 @@ array([ 2., 5.]) In [22]: -``` +```py mean(a) ``` Out[22]: -``` +```py 3.500 ``` @@ -324,14 +324,14 @@ Out[22]: In [23]: -``` +```py average(a, axis = 0) ``` Out[23]: -``` +```py array([ 2.5, 3.5, 4.5]) ``` @@ -339,14 +339,14 @@ array([ 2.5, 3.5, 4.5]) In [24]: -``` +```py average(a, axis = 0, weights=[1,2]) ``` Out[24]: -``` +```py array([ 3., 4., 5.]) ``` @@ -356,14 +356,14 @@ array([ 3., 4., 5.]) In [25]: -``` +```py a.std(axis=1) ``` Out[25]: -``` +```py array([ 0.816, 0.816]) ``` @@ -371,14 +371,14 @@ array([ 0.816, 0.816]) In [26]: -``` +```py a.var(axis=1) ``` Out[26]: -``` +```py array([ 0.667, 0.667]) ``` @@ -386,27 +386,27 @@ array([ 0.667, 0.667]) In [27]: -``` +```py var(a, axis=1) ``` Out[27]: -``` +```py array([ 0.667, 0.667]) ``` In [28]: -``` +```py std(a, axis=1) ``` Out[28]: -``` +```py array([ 0.816, 0.816]) ``` @@ -416,28 +416,28 @@ array([ 0.816, 0.816]) In [29]: -``` +```py a ``` Out[29]: -``` +```py array([[1, 2, 3], [4, 5, 6]]) ``` In [30]: -``` +```py a.clip(3,5) ``` Out[30]: -``` +```py array([[3, 3, 3], [4, 5, 5]]) ``` @@ -450,27 +450,27 @@ array([[3, 3, 3], In [31]: -``` +```py a.ptp(axis=1) ``` Out[31]: -``` +```py array([2, 2]) ``` In [32]: -``` +```py a.ptp() ``` Out[32]: -``` +```py 5 ``` @@ -480,7 +480,7 @@ Out[32]: In [33]: -``` +```py a = array([1.35, 2.5, 1.5]) ``` @@ -491,14 +491,14 @@ a = array([1.35, 2.5, 1.5]) In [34]: -``` +```py a.round() ``` Out[34]: -``` +```py array([ 1., 2., 2.]) ``` @@ -506,13 +506,13 @@ array([ 1., 2., 2.]) In [35]: -``` +```py a.round(decimals=1) ``` Out[35]: -``` +```py array([ 1.4, 2.5, 1.5]) ``` \ No newline at end of file diff --git a/docs/da/034.md b/docs/da/034.md index f66ad5054..00a0085f2 100644 --- a/docs/da/034.md +++ b/docs/da/034.md @@ -2,12 +2,12 @@ In [1]: -``` +```py %pylab ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -19,7 +19,7 @@ Populating the interactive namespace from numpy and matplotlib In [2]: -``` +```py names = array(['bob', 'sue', 'jan', 'ad']) weights = array([20.8, 93.2, 53.4, 61.8]) @@ -29,7 +29,7 @@ sort(weights) Out[2]: -``` +```py array([ 20.8, 53.4, 61.8, 93.2]) ``` @@ -41,7 +41,7 @@ array([ 20.8, 53.4, 61.8, 93.2]) In [3]: -``` +```py ordered_indices = argsort(weights) ordered_indices @@ -49,7 +49,7 @@ ordered_indices Out[3]: -``` +```py array([0, 2, 3, 1], dtype=int64) ``` @@ -57,27 +57,27 @@ array([0, 2, 3, 1], dtype=int64) In [4]: -``` +```py weights[ordered_indices] ``` Out[4]: -``` +```py array([ 20.8, 53.4, 61.8, 93.2]) ``` In [5]: -``` +```py names[ordered_indices] ``` Out[5]: -``` +```py array(['bob', 'jan', 'ad', 'sue'], dtype='|S3') ``` @@ -86,14 +86,14 @@ array(['bob', 'jan', 'ad', 'sue'], In [6]: -``` +```py weights ``` Out[6]: -``` +```py array([ 20.8, 93.2, 53.4, 61.8]) ``` @@ -103,7 +103,7 @@ array([ 20.8, 93.2, 53.4, 61.8]) In [7]: -``` +```py data = array([20.8, 93.2, 53.4, 61.8]) data.argsort() @@ -111,7 +111,7 @@ data.argsort() Out[7]: -``` +```py array([0, 2, 3, 1], dtype=int64) ``` @@ -119,14 +119,14 @@ array([0, 2, 3, 1], dtype=int64) In [8]: -``` +```py data ``` Out[8]: -``` +```py array([ 20.8, 93.2, 53.4, 61.8]) ``` @@ -134,21 +134,21 @@ array([ 20.8, 93.2, 53.4, 61.8]) In [9]: -``` +```py data.sort() ``` In [10]: -``` +```py data ``` Out[10]: -``` +```py array([ 20.8, 53.4, 61.8, 93.2]) ``` @@ -158,7 +158,7 @@ array([ 20.8, 53.4, 61.8, 93.2]) In [11]: -``` +```py a = array([ [.2, .1, .5], [.4, .8, .3], @@ -170,7 +170,7 @@ a Out[11]: -``` +```py array([[ 0.2, 0.1, 0.5], [ 0.4, 0.8, 0.3], [ 0.9, 0.6, 0.7]]) @@ -180,14 +180,14 @@ array([[ 0.2, 0.1, 0.5], In [12]: -``` +```py sort(a) ``` Out[12]: -``` +```py array([[ 0.1, 0.2, 0.5], [ 0.3, 0.4, 0.8], [ 0.6, 0.7, 0.9]]) @@ -197,14 +197,14 @@ array([[ 0.1, 0.2, 0.5], In [13]: -``` +```py sort(a, axis = 0) ``` Out[13]: -``` +```py array([[ 0.2, 0.1, 0.3], [ 0.4, 0.6, 0.5], [ 0.9, 0.8, 0.7]]) @@ -212,7 +212,7 @@ array([[ 0.2, 0.1, 0.3], ## searchsorted 函数 -``` +```py searchsorted(sorted_array, values) ``` @@ -220,7 +220,7 @@ searchsorted(sorted_array, values) In [14]: -``` +```py sorted_array = linspace(0,1,5) values = array([.1,.8,.3,.12,.5,.25]) @@ -228,14 +228,14 @@ values = array([.1,.8,.3,.12,.5,.25]) In [15]: -``` +```py searchsorted(sorted_array, values) ``` Out[15]: -``` +```py array([1, 4, 2, 1, 2, 1], dtype=int64) ``` @@ -257,7 +257,7 @@ array([1, 4, 2, 1, 2, 1], dtype=int64) In [16]: -``` +```py from numpy.random import rand data = rand(100) data.sort() @@ -268,7 +268,7 @@ data.sort() In [17]: -``` +```py bounds = .4, .6 bounds @@ -276,7 +276,7 @@ bounds Out[17]: -``` +```py (0.4, 0.6) ``` @@ -284,7 +284,7 @@ Out[17]: In [18]: -``` +```py low_idx, high_idx = searchsorted(data, bounds) ``` @@ -293,14 +293,14 @@ low_idx, high_idx = searchsorted(data, bounds) In [19]: -``` +```py data[low_idx:high_idx] ``` Out[19]: -``` +```py array([ 0.41122674, 0.4395727 , 0.45609773, 0.45707137, 0.45772076, 0.46029997, 0.46757401, 0.47525517, 0.4969198 , 0.53068779, 0.55764166, 0.56288568, 0.56506548, 0.57003042, 0.58035233, diff --git a/docs/da/035.md b/docs/da/035.md index 6250e7719..ff1f6d077 100644 --- a/docs/da/035.md +++ b/docs/da/035.md @@ -2,12 +2,12 @@ In [1]: -``` +```py %pylab ``` -``` +```py Using matplotlib backend: Qt4Agg Populating the interactive namespace from numpy and matplotlib @@ -17,7 +17,7 @@ Populating the interactive namespace from numpy and matplotlib In [2]: -``` +```py a = arange(6) a @@ -25,7 +25,7 @@ a Out[2]: -``` +```py array([0, 1, 2, 3, 4, 5]) ``` @@ -33,7 +33,7 @@ array([0, 1, 2, 3, 4, 5]) In [3]: -``` +```py a.shape = 2,3 a @@ -41,7 +41,7 @@ a Out[3]: -``` +```py array([[0, 1, 2], [3, 4, 5]]) ``` @@ -50,14 +50,14 @@ array([[0, 1, 2], In [4]: -``` +```py a.reshape(3,2) ``` Out[4]: -``` +```py array([[0, 1], [2, 3], [4, 5]]) @@ -65,14 +65,14 @@ array([[0, 1], In [5]: -``` +```py a ``` Out[5]: -``` +```py array([[0, 1, 2], [3, 4, 5]]) ``` @@ -81,12 +81,12 @@ array([[0, 1, 2], In [6]: -``` +```py a.reshape(4,2) ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -99,7 +99,7 @@ ValueError: total size of new array must be unchanged In [7]: -``` +```py a = arange(3) shape(a) @@ -107,13 +107,13 @@ shape(a) Out[7]: -``` +```py (3L,) ``` In [8]: -``` +```py y = a[newaxis, :] shape(y) @@ -121,7 +121,7 @@ shape(y) Out[8]: -``` +```py (1L, 3L) ``` @@ -129,7 +129,7 @@ Out[8]: In [9]: -``` +```py y = a[:, newaxis] shape(y) @@ -137,7 +137,7 @@ shape(y) Out[9]: -``` +```py (3L, 1L) ``` @@ -145,7 +145,7 @@ Out[9]: In [10]: -``` +```py y = a[newaxis, newaxis, :] shape(y) @@ -153,7 +153,7 @@ shape(y) Out[10]: -``` +```py (1L, 1L, 3L) ``` @@ -161,7 +161,7 @@ Out[10]: In [11]: -``` +```py a = arange(6) a.shape = (2,1,3) @@ -169,7 +169,7 @@ a.shape = (2,1,3) In [12]: -``` +```py b = a.squeeze() b.shape @@ -177,7 +177,7 @@ b.shape Out[12]: -``` +```py (2L, 3L) ``` @@ -189,14 +189,14 @@ squeeze 返回一个将所有长度为1的维度去除的新数组。 In [13]: -``` +```py a ``` Out[13]: -``` +```py array([[[0, 1, 2]], [[3, 4, 5]]]) @@ -206,14 +206,14 @@ array([[[0, 1, 2]], In [14]: -``` +```py a.transpose() ``` Out[14]: -``` +```py array([[[0, 3]], [[1, 4]], @@ -225,14 +225,14 @@ array([[[0, 3]], In [15]: -``` +```py a.T ``` Out[15]: -``` +```py array([[[0, 3]], [[1, 4]], @@ -247,7 +247,7 @@ array([[[0, 3]], In [16]: -``` +```py a = arange(60) a @@ -255,7 +255,7 @@ a Out[16]: -``` +```py array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, @@ -264,7 +264,7 @@ array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, In [17]: -``` +```py a.shape = 3,4,5 a @@ -272,7 +272,7 @@ a Out[17]: -``` +```py array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], @@ -291,7 +291,7 @@ array([[[ 0, 1, 2, 3, 4], In [18]: -``` +```py b = a.T b.shape @@ -299,7 +299,7 @@ b.shape Out[18]: -``` +```py (5L, 4L, 3L) ``` @@ -309,7 +309,7 @@ Out[18]: In [19]: -``` +```py a = arange(6) a.shape = (2,3) a @@ -318,7 +318,7 @@ a Out[19]: -``` +```py array([[0, 1, 2], [3, 4, 5]]) ``` @@ -327,7 +327,7 @@ array([[0, 1, 2], In [20]: -``` +```py b = a.T b[0,1] = 30 @@ -337,14 +337,14 @@ b[0,1] = 30 In [21]: -``` +```py a ``` Out[21]: -``` +```py array([[ 0, 1, 2], [30, 4, 5]]) ``` @@ -353,7 +353,7 @@ array([[ 0, 1, 2], 有时我们需要将不同的数组按照一定的顺序连接起来: -``` +```py concatenate((a0,a1,...,aN), axis=0) ``` @@ -363,7 +363,7 @@ concatenate((a0,a1,...,aN), axis=0) In [22]: -``` +```py x = array([ [0,1,2], [10,11,12] @@ -377,7 +377,7 @@ print y.shape ``` -``` +```py (2L, 3L) (2L, 3L) @@ -387,7 +387,7 @@ print y.shape In [23]: -``` +```py z = concatenate((x,y)) z @@ -395,7 +395,7 @@ z Out[23]: -``` +```py array([[ 0, 1, 2], [10, 11, 12], [50, 51, 52], @@ -404,14 +404,14 @@ array([[ 0, 1, 2], In [24]: -``` +```py z.shape ``` Out[24]: -``` +```py (4L, 3L) ``` @@ -419,7 +419,7 @@ Out[24]: In [25]: -``` +```py z = concatenate((x,y), axis=1) z @@ -427,21 +427,21 @@ z Out[25]: -``` +```py array([[ 0, 1, 2, 50, 51, 52], [10, 11, 12, 60, 61, 62]]) ``` In [26]: -``` +```py z.shape ``` Out[26]: -``` +```py (2L, 6L) ``` @@ -449,21 +449,21 @@ Out[26]: In [27]: -``` +```py z = array((x,y)) ``` In [28]: -``` +```py z.shape ``` Out[28]: -``` +```py (2L, 2L, 3L) ``` @@ -475,40 +475,40 @@ Out[28]: In [29]: -``` +```py vstack((x, y)).shape ``` Out[29]: -``` +```py (4L, 3L) ``` In [30]: -``` +```py hstack((x, y)).shape ``` Out[30]: -``` +```py (2L, 6L) ``` In [31]: -``` +```py dstack((x, y)).shape ``` Out[31]: -``` +```py (2L, 3L, 2L) ``` @@ -518,7 +518,7 @@ Out[31]: In [32]: -``` +```py a = array([[0,1], [2,3]]) b = a.flatten() @@ -528,7 +528,7 @@ b Out[32]: -``` +```py array([0, 1, 2, 3]) ``` @@ -536,14 +536,14 @@ array([0, 1, 2, 3]) In [33]: -``` +```py b[0] = 10 print b print a ``` -``` +```py [10 1 2 3] [[0 1] [2 3]] @@ -556,14 +556,14 @@ print a In [34]: -``` +```py a.flat ``` Out[34]: -``` +```py ``` @@ -571,21 +571,21 @@ Out[34]: In [35]: -``` +```py b = a.flat ``` In [36]: -``` +```py b[0] ``` Out[36]: -``` +```py 0 ``` @@ -593,13 +593,13 @@ Out[36]: In [37]: -``` +```py b[0] = 10 print a ``` -``` +```py [[10 1] [ 2 3]] @@ -607,14 +607,14 @@ print a In [38]: -``` +```py a.flat[:] ``` Out[38]: -``` +```py array([10, 1, 2, 3]) ``` @@ -624,7 +624,7 @@ array([10, 1, 2, 3]) In [39]: -``` +```py a = array([[0,1], [2,3]]) b = a.ravel() @@ -634,7 +634,7 @@ b Out[39]: -``` +```py array([0, 1, 2, 3]) ``` @@ -642,7 +642,7 @@ array([0, 1, 2, 3]) In [40]: -``` +```py b[0] = 10 a @@ -650,7 +650,7 @@ a Out[40]: -``` +```py array([[10, 1], [ 2, 3]]) ``` @@ -659,7 +659,7 @@ array([[10, 1], In [41]: -``` +```py a = array([[0,1], [2,3]]) aa = a.transpose() @@ -670,41 +670,41 @@ b Out[41]: -``` +```py array([0, 2, 1, 3]) ``` In [42]: -``` +```py b[0] = 10 ``` In [43]: -``` +```py aa ``` Out[43]: -``` +```py array([[0, 2], [1, 3]]) ``` In [44]: -``` +```py a ``` Out[44]: -``` +```py array([[0, 1], [2, 3]]) ``` @@ -717,7 +717,7 @@ array([[0, 1], In [45]: -``` +```py x = 1 atleast_1d(x) @@ -725,13 +725,13 @@ atleast_1d(x) Out[45]: -``` +```py array([1]) ``` In [46]: -``` +```py a = array([1,2,3]) b = atleast_2d(a) b.shape @@ -740,40 +740,40 @@ b.shape Out[46]: -``` +```py (1L, 3L) ``` In [47]: -``` +```py b ``` Out[47]: -``` +```py array([[1, 2, 3]]) ``` In [48]: -``` +```py c = atleast_3d(b) ``` In [49]: -``` +```py c.shape ``` Out[49]: -``` +```py (1L, 3L, 1L) ``` diff --git a/docs/da/036.md b/docs/da/036.md index 6bf0c14a7..7ceb92986 100644 --- a/docs/da/036.md +++ b/docs/da/036.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np ``` @@ -13,7 +13,7 @@ import numpy as np In [2]: -``` +```py a = np.array([11,21,31,12,22,32,13,23,33]) a.shape = 3,3 a @@ -22,7 +22,7 @@ a Out[2]: -``` +```py array([[11, 21, 31], [12, 22, 32], [13, 23, 33]]) @@ -32,14 +32,14 @@ array([[11, 21, 31], In [3]: -``` +```py a.diagonal() ``` Out[3]: -``` +```py array([11, 22, 33]) ``` @@ -47,27 +47,27 @@ array([11, 22, 33]) In [4]: -``` +```py a.diagonal(offset=1) ``` Out[4]: -``` +```py array([21, 32]) ``` In [5]: -``` +```py a.diagonal(offset=-1) ``` Out[5]: -``` +```py array([12, 23]) ``` @@ -75,7 +75,7 @@ array([12, 23]) In [6]: -``` +```py i = [0,1,2] a[i, i] @@ -83,7 +83,7 @@ a[i, i] Out[6]: -``` +```py array([11, 22, 33]) ``` @@ -91,7 +91,7 @@ array([11, 22, 33]) In [7]: -``` +```py a[i, i] = 2 a @@ -99,7 +99,7 @@ a Out[7]: -``` +```py array([[ 2, 21, 31], [12, 2, 32], [13, 23, 2]]) @@ -109,7 +109,7 @@ array([[ 2, 21, 31], In [8]: -``` +```py i = np.array([0,1]) a[i, i + 1] = 1 a @@ -118,7 +118,7 @@ a Out[8]: -``` +```py array([[ 2, 1, 31], [12, 2, 1], [13, 23, 2]]) @@ -126,7 +126,7 @@ array([[ 2, 1, 31], In [9]: -``` +```py a[i + 1, i] = -1 a @@ -134,7 +134,7 @@ a Out[9]: -``` +```py array([[ 2, 1, 31], [-1, 2, 1], [13, -1, 2]]) diff --git a/docs/da/037.md b/docs/da/037.md index e0649df6c..146b3190b 100644 --- a/docs/da/037.md +++ b/docs/da/037.md @@ -4,14 +4,14 @@ In [1]: -``` +```py import numpy as np ``` In [2]: -``` +```py a = np.array([[1,2], [3,4]], dtype = np.uint8) @@ -22,14 +22,14 @@ a = np.array([[1,2], In [3]: -``` +```py a.tostring() ``` Out[3]: -``` +```py '\x01\x02\x03\x04' ``` @@ -37,14 +37,14 @@ Out[3]: In [4]: -``` +```py a.tostring(order='F') ``` Out[4]: -``` +```py '\x01\x03\x02\x04' ``` @@ -56,7 +56,7 @@ Out[4]: In [5]: -``` +```py s = a.tostring() a = np.fromstring(s, dtype=np.uint8) @@ -66,7 +66,7 @@ a Out[5]: -``` +```py array([1, 2, 3, 4], dtype=uint8) ``` @@ -74,7 +74,7 @@ array([1, 2, 3, 4], dtype=uint8) In [6]: -``` +```py a.shape = 2,2 a @@ -82,7 +82,7 @@ a Out[6]: -``` +```py array([[1, 2], [3, 4]], dtype=uint8) ``` diff --git a/docs/da/038.md b/docs/da/038.md index 6b35114dc..30d7fe2a5 100644 --- a/docs/da/038.md +++ b/docs/da/038.md @@ -62,7 +62,7 @@ In [1]: -``` +```py from numpy import * ``` @@ -71,7 +71,7 @@ from numpy import * In [2]: -``` +```py a = array([[0, 1, 2, 3], [4, 5, 6, 7]]) a @@ -79,7 +79,7 @@ a Out[2]: -``` +```py array([[0, 1, 2, 3], [4, 5, 6, 7]]) ``` @@ -88,14 +88,14 @@ array([[0, 1, 2, 3], In [3]: -``` +```py a.dtype ``` Out[3]: -``` +```py dtype('int32') ``` @@ -103,14 +103,14 @@ dtype('int32') In [4]: -``` +```py a.shape ``` Out[4]: -``` +```py (2L, 4L) ``` @@ -118,14 +118,14 @@ Out[4]: In [5]: -``` +```py a.size ``` Out[5]: -``` +```py 8 ``` @@ -133,14 +133,14 @@ Out[5]: In [6]: -``` +```py a.itemsize ``` Out[6]: -``` +```py 4 ``` @@ -148,14 +148,14 @@ Out[6]: In [7]: -``` +```py a.nbytes ``` Out[7]: -``` +```py 32 ``` @@ -163,14 +163,14 @@ Out[7]: In [8]: -``` +```py a.ndim ``` Out[8]: -``` +```py 2 ``` @@ -178,13 +178,13 @@ Out[8]: In [9]: -``` +```py for row in a: print row ``` -``` +```py [0 1 2 3] [4 5 6 7] @@ -194,13 +194,13 @@ for row in a: In [10]: -``` +```py for elt in a.flat: print elt ``` -``` +```py 0 1 2 @@ -216,27 +216,27 @@ for elt in a.flat: In [11]: -``` +```py a.flatten() ``` Out[11]: -``` +```py array([0, 1, 2, 3, 4, 5, 6, 7]) ``` In [12]: -``` +```py a.ravel() ``` Out[12]: -``` +```py array([0, 1, 2, 3, 4, 5, 6, 7]) ``` @@ -244,7 +244,7 @@ array([0, 1, 2, 3, 4, 5, 6, 7]) In [13]: -``` +```py a.resize((4,2)) a @@ -252,7 +252,7 @@ a Out[13]: -``` +```py array([[0, 1], [2, 3], [4, 5], @@ -263,14 +263,14 @@ array([[0, 1], In [14]: -``` +```py a.swapaxes(0,1) ``` Out[14]: -``` +```py array([[0, 2, 4, 6], [1, 3, 5, 7]]) ``` @@ -279,14 +279,14 @@ array([[0, 2, 4, 6], In [15]: -``` +```py a.transpose() ``` Out[15]: -``` +```py array([[0, 2, 4, 6], [1, 3, 5, 7]]) ``` @@ -295,21 +295,21 @@ array([[0, 2, 4, 6], In [16]: -``` +```py a.T ``` Out[16]: -``` +```py array([[0, 2, 4, 6], [1, 3, 5, 7]]) ``` In [17]: -``` +```py a2 = array([1,2,3]) a2.shape @@ -317,13 +317,13 @@ a2.shape Out[17]: -``` +```py (3L,) ``` In [18]: -``` +```py a2.resize((1,3,1)) a2.shape @@ -331,7 +331,7 @@ a2.shape Out[18]: -``` +```py (1L, 3L, 1L) ``` @@ -339,7 +339,7 @@ Out[18]: In [19]: -``` +```py a2 = a2.squeeze() a2.shape @@ -347,7 +347,7 @@ a2.shape Out[19]: -``` +```py (3L,) ``` @@ -357,7 +357,7 @@ Out[19]: In [20]: -``` +```py b = a.copy() b @@ -365,7 +365,7 @@ b Out[20]: -``` +```py array([[0, 1], [2, 3], [4, 5], @@ -376,7 +376,7 @@ array([[0, 1], In [21]: -``` +```py b[0][0] = -1 b # First value changed @@ -384,7 +384,7 @@ b # First value changed Out[21]: -``` +```py array([[-1, 1], [ 2, 3], [ 4, 5], @@ -393,14 +393,14 @@ array([[-1, 1], In [22]: -``` +```py a # original not changed because b is a copy ``` Out[22]: -``` +```py array([[0, 1], [2, 3], [4, 5], @@ -411,7 +411,7 @@ array([[0, 1], In [23]: -``` +```py b.fill(4) b @@ -419,7 +419,7 @@ b Out[23]: -``` +```py array([[4, 4], [4, 4], [4, 4], @@ -432,14 +432,14 @@ array([[4, 4], In [24]: -``` +```py a.tolist() ``` Out[24]: -``` +```py [[0, 1], [2, 3], [4, 5], [6, 7]] ``` @@ -447,14 +447,14 @@ Out[24]: In [25]: -``` +```py a.tostring() ``` Out[25]: -``` +```py '\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00' ``` @@ -462,14 +462,14 @@ Out[25]: In [26]: -``` +```py a.astype(float) ``` Out[26]: -``` +```py array([[ 0., 1.], [ 2., 3.], [ 4., 5.], @@ -478,7 +478,7 @@ array([[ 0., 1.], In [27]: -``` +```py b = a.copy() b.byteswap(False) @@ -486,7 +486,7 @@ b.byteswap(False) Out[27]: -``` +```py array([[ 0, 16777216], [ 33554432, 50331648], [ 67108864, 83886080], @@ -497,14 +497,14 @@ array([[ 0, 16777216], In [28]: -``` +```py a.view(dtype=int16) ``` Out[28]: -``` +```py array([[0, 0, 1, 0], [2, 0, 3, 0], [4, 0, 5, 0], @@ -517,7 +517,7 @@ array([[0, 0, 1, 0], In [29]: -``` +```py b = array([1+2j, 3+4j, 5+6j]) b.real @@ -525,7 +525,7 @@ b.real Out[29]: -``` +```py array([ 1., 3., 5.]) ``` @@ -533,14 +533,14 @@ array([ 1., 3., 5.]) In [30]: -``` +```py b.imag ``` Out[30]: -``` +```py array([ 2., 4., 6.]) ``` @@ -548,27 +548,27 @@ array([ 2., 4., 6.]) In [31]: -``` +```py b.conj() ``` Out[31]: -``` +```py array([ 1.-2.j, 3.-4.j, 5.-6.j]) ``` In [32]: -``` +```py b.conjugate() ``` Out[32]: -``` +```py array([ 1.-2.j, 3.-4.j, 5.-6.j]) ``` @@ -578,7 +578,7 @@ array([ 1.-2.j, 3.-4.j, 5.-6.j]) In [33]: -``` +```py a.dump("file.txt") ``` @@ -587,14 +587,14 @@ a.dump("file.txt") In [34]: -``` +```py a.dumps() ``` Out[34]: -``` +```py '\x80\x02cnumpy.core.multiarray\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x01\x8a\x01\x04\x8a\x01\x02\x86cnumpy\ndtype\nq\x04U\x02i4K\x00K\x01\x87Rq\x05(K\x03U\x01 ``` @@ -1209,7 +1209,7 @@ YII= In [11]: -``` +```py x_ticks = np.linspace(-1, 1, 5) y_ticks = np.linspace(-1, 1, 5) @@ -1219,27 +1219,27 @@ x, y = np.meshgrid(x_ticks, y_ticks, sparse=True) In [12]: -``` +```py x ``` Out[12]: -``` +```py array([[-1\. , -0.5, 0\. , 0.5, 1\. ]]) ``` In [13]: -``` +```py y ``` Out[13]: -``` +```py array([[-1\. ], [-0.5], [ 0\. ], @@ -1253,7 +1253,7 @@ array([[-1\. ], In [14]: -``` +```py x_ticks = np.linspace(-10, 10, 51) y_ticks = np.linspace(-10, 10, 51) @@ -1272,14 +1272,14 @@ ax.set_zlabel('z') ``` -``` +```py c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:9: RuntimeWarning: invalid value encountered in divide ``` Out[14]: -``` +```py ``` @@ -2282,7 +2282,7 @@ YII= **Matlab**中有 `meshgrid` 的用法: -``` +```py meshgrid(-1:.5:1, -1:.5:1) ``` @@ -2295,21 +2295,21 @@ meshgrid(-1:.5:1, -1:.5:1) In [15]: -``` +```py x, y = np.ogrid[-1:1:.5, -1:1:.5] ``` In [16]: -``` +```py x ``` Out[16]: -``` +```py array([[-1\. ], [-0.5], [ 0\. ], @@ -2318,14 +2318,14 @@ array([[-1\. ], In [17]: -``` +```py y ``` Out[17]: -``` +```py array([[-1\. , -0.5, 0\. , 0.5]]) ``` @@ -2339,21 +2339,21 @@ array([[-1\. , -0.5, 0\. , 0.5]]) In [18]: -``` +```py x, y = np.ogrid[-1:1:5j, -1:1:5j] ``` In [19]: -``` +```py x, y ``` Out[19]: -``` +```py (array([[-1\. ], [-0.5], [ 0\. ], @@ -2367,7 +2367,7 @@ Out[19]: In [20]: -``` +```py # exchange here y, x = np.ogrid[-10:10:51j, -10:10:51j] @@ -2384,14 +2384,14 @@ ax.set_zlabel('z') ``` -``` +```py c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:9: RuntimeWarning: invalid value encountered in divide ``` Out[20]: -``` +```py ``` @@ -3395,14 +3395,14 @@ YII= In [21]: -``` +```py np.r_[0:1:.1] ``` Out[21]: -``` +```py array([ 0\. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) ``` @@ -3410,14 +3410,14 @@ array([ 0\. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) In [22]: -``` +```py np.r_[0:1:5j] ``` Out[22]: -``` +```py array([ 0\. , 0.25, 0.5 , 0.75, 1\. ]) ``` @@ -3425,14 +3425,14 @@ array([ 0\. , 0.25, 0.5 , 0.75, 1\. ]) In [23]: -``` +```py np.r_[(3,22,11), 4.0, [15, 6]] ``` Out[23]: -``` +```py array([ 3., 22., 11., 4., 15., 6.]) ``` @@ -3440,14 +3440,14 @@ array([ 3., 22., 11., 4., 15., 6.]) In [24]: -``` +```py np.c_[1:3:5j] ``` Out[24]: -``` +```py array([[ 1\. ], [ 1.5], [ 2\. ], @@ -3457,7 +3457,7 @@ array([[ 1\. ], ## ones , zeros -``` +```py ones(shape, dtype=float64) zeros(shape, dtype=float64) @@ -3467,27 +3467,27 @@ zeros(shape, dtype=float64) In [25]: -``` +```py np.zeros(3) ``` Out[25]: -``` +```py array([ 0., 0., 0.]) ``` In [26]: -``` +```py np.ones([2,3], dtype=np.float32) ``` Out[26]: -``` +```py array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) ``` @@ -3496,21 +3496,21 @@ array([[ 1., 1., 1.], In [27]: -``` +```py np.ones([2,3]) * 5 ``` Out[27]: -``` +```py array([[ 5., 5., 5.], [ 5., 5., 5.]]) ``` ## empty -``` +```py empty(shape, dtype=float64, order='C') ``` @@ -3518,7 +3518,7 @@ empty(shape, dtype=float64, order='C') In [28]: -``` +```py a = np.empty(2) a @@ -3526,13 +3526,13 @@ a Out[28]: -``` +```py array([-0.03412165, 0.05516321]) ``` In [29]: -``` +```py a.fill(5) a @@ -3540,7 +3540,7 @@ a Out[29]: -``` +```py array([ 5., 5.]) ``` @@ -3548,7 +3548,7 @@ array([ 5., 5.]) In [30]: -``` +```py a[:] = 5 a @@ -3556,13 +3556,13 @@ a Out[30]: -``` +```py array([ 5., 5.]) ``` ## empty`_`like, ones`_`like, zeros`_`like -``` +```py empty_like(a) ones_like(a) zeros_like(a) @@ -3572,7 +3572,7 @@ zeros_like(a) In [31]: -``` +```py a = np.arange(0, 10, 2.5) a @@ -3580,52 +3580,52 @@ a Out[31]: -``` +```py array([ 0\. , 2.5, 5\. , 7.5]) ``` In [32]: -``` +```py np.empty_like(a) ``` Out[32]: -``` +```py array([ 0., 0., 0., 0.]) ``` In [33]: -``` +```py np.zeros_like(a) ``` Out[33]: -``` +```py array([ 0., 0., 0., 0.]) ``` In [34]: -``` +```py np.ones_like(a) ``` Out[34]: -``` +```py array([ 1., 1., 1., 1.]) ``` ## identity -``` +```py indentity(n, dtype=float64) ``` @@ -3633,14 +3633,14 @@ indentity(n, dtype=float64) In [35]: -``` +```py np.identity(3) ``` Out[35]: -``` +```py array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) diff --git a/docs/da/040.md b/docs/da/040.md index 950eda435..c77bc1b04 100644 --- a/docs/da/040.md +++ b/docs/da/040.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np a = np.array([[1,2,4], [2,5,3], @@ -16,7 +16,7 @@ A Out[1]: -``` +```py matrix([[1, 2, 4], [2, 5, 3], [7, 8, 9]]) @@ -26,7 +26,7 @@ matrix([[1, 2, 4], In [2]: -``` +```py A = np.mat('1,2,4;2,5,3;7,8,9') A @@ -34,7 +34,7 @@ A Out[2]: -``` +```py matrix([[1, 2, 4], [2, 5, 3], [7, 8, 9]]) @@ -44,7 +44,7 @@ matrix([[1, 2, 4], In [3]: -``` +```py a = np.array([[ 1, 2], [ 3, 4]]) b = np.array([[10,20], @@ -56,7 +56,7 @@ np.bmat('a,b;b,a') Out[3]: -``` +```py matrix([[ 1, 2, 10, 20], [ 3, 4, 30, 40], [10, 20, 1, 2], @@ -67,7 +67,7 @@ matrix([[ 1, 2, 10, 20], In [4]: -``` +```py x = np.array([[1], [2], [3]]) x @@ -75,7 +75,7 @@ x Out[4]: -``` +```py array([[1], [2], [3]]) @@ -83,14 +83,14 @@ array([[1], In [5]: -``` +```py A * x ``` Out[5]: -``` +```py matrix([[17], [21], [50]]) @@ -100,12 +100,12 @@ matrix([[17], In [6]: -``` +```py print A * A.I ``` -``` +```py [[ 1.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 1.00000000e+00 2.08166817e-17] [ 2.22044605e-16 -8.32667268e-17 1.00000000e+00]] @@ -116,12 +116,12 @@ print A * A.I In [7]: -``` +```py print A ** 4 ``` -``` +```py [[ 6497 9580 9836] [ 7138 10561 10818] [18434 27220 27945]] diff --git a/docs/da/041.md b/docs/da/041.md index 7f5571329..fae7ca657 100644 --- a/docs/da/041.md +++ b/docs/da/041.md @@ -2,14 +2,14 @@ In [1]: -``` +```py import numpy as np ``` ## 三角函数 -``` +```py sin(x) cos(x) tan(x) @@ -29,7 +29,7 @@ arctan2(x,y) ## 向量操作 -``` +```py dot(x,y) inner(x,y) cross(x,y) @@ -41,7 +41,7 @@ tensordot(x,y[,axis]) ## 其他操作 -``` +```py exp(x) log(x) log10(x) @@ -62,7 +62,7 @@ minimum(x,y) In [2]: -``` +```py x = np.array([1,2,3]) y = np.array([4,5,6]) np.hypot(x,y) @@ -71,13 +71,13 @@ np.hypot(x,y) Out[2]: -``` +```py array([ 4.12310563, 5.38516481, 6.70820393]) ``` ## 类型处理 -``` +```py iscomplexobj iscomplex isrealobj @@ -100,14 +100,14 @@ typename In [3]: -``` +```py np.inf ``` Out[3]: -``` +```py inf ``` @@ -115,14 +115,14 @@ inf In [4]: -``` +```py -np.inf ``` Out[4]: -``` +```py -inf ``` @@ -130,14 +130,14 @@ Out[4]: In [5]: -``` +```py np.nan ``` Out[5]: -``` +```py nan ``` @@ -145,40 +145,40 @@ nan In [6]: -``` +```py np.isinf(1.0) ``` Out[6]: -``` +```py False ``` In [7]: -``` +```py np.isinf(np.inf) ``` Out[7]: -``` +```py True ``` In [8]: -``` +```py np.isinf(-np.inf) ``` Out[8]: -``` +```py True ``` @@ -186,12 +186,12 @@ True In [9]: -``` +```py np.array([0]) / 0.0 ``` -``` +```py c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:1: RuntimeWarning: invalid value encountered in divide if __name__ == '__main__': @@ -199,7 +199,7 @@ c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:1: RuntimeWarning: inv Out[9]: -``` +```py array([ nan]) ``` @@ -209,14 +209,14 @@ array([ nan]) In [10]: -``` +```py a = np.arange(5.0) b = a / 0.0 b ``` -``` +```py c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:2: RuntimeWarning: divide by zero encountered in divide from IPython.kernel.zmq import kernelapp as app c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:2: RuntimeWarning: invalid value encountered in divide @@ -226,7 +226,7 @@ c:\Miniconda\lib\site-packages\IPython\kernel\__main__.py:2: RuntimeWarning: inv Out[10]: -``` +```py array([ nan, inf, inf, inf, inf]) ``` @@ -234,14 +234,14 @@ array([ nan, inf, inf, inf, inf]) In [11]: -``` +```py b == np.nan ``` Out[11]: -``` +```py array([False, False, False, False, False], dtype=bool) ``` @@ -249,20 +249,20 @@ array([False, False, False, False, False], dtype=bool) In [12]: -``` +```py np.isnan(b) ``` Out[12]: -``` +```py array([ True, False, False, False, False], dtype=bool) ``` ## 修改形状 -``` +```py atleast_1d atleast_2d atleast_3d @@ -282,7 +282,7 @@ squeeze ## 其他有用函数 -``` +```py fix mod amax diff --git a/docs/da/042.md b/docs/da/042.md index eb1cff76a..9e0511273 100644 --- a/docs/da/042.md +++ b/docs/da/042.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np def sinc(x): @@ -20,27 +20,27 @@ def sinc(x): In [2]: -``` +```py sinc(0.0) ``` Out[2]: -``` +```py 1.0 ``` In [3]: -``` +```py sinc(3.0) ``` Out[3]: -``` +```py 3.8981718325193755e-17 ``` @@ -48,13 +48,13 @@ Out[3]: In [4]: -``` +```py x = np.array([1,2,3]) sinc(x) ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -75,7 +75,7 @@ ValueError: The truth value of an array with more than one element is ambiguous. In [5]: -``` +```py vsinc = np.vectorize(sinc) vsinc(x) @@ -83,7 +83,7 @@ vsinc(x) Out[5]: -``` +```py array([ 3.89817183e-17, -3.89817183e-17, 3.89817183e-17]) ``` @@ -91,7 +91,7 @@ array([ 3.89817183e-17, -3.89817183e-17, 3.89817183e-17]) In [6]: -``` +```py import matplotlib.pyplot as plt %matplotlib inline @@ -102,7 +102,7 @@ plt.plot(x, vsinc(x)) Out[6]: -``` +```py [] ``` diff --git a/docs/da/043.md b/docs/da/043.md index c6e027762..8554150a5 100644 --- a/docs/da/043.md +++ b/docs/da/043.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np ``` @@ -22,7 +22,7 @@ import numpy as np In [2]: -``` +```py a = np.array([1,2]) a * 3 @@ -30,7 +30,7 @@ a * 3 Out[2]: -``` +```py array([3, 6]) ``` @@ -38,7 +38,7 @@ array([3, 6]) In [3]: -``` +```py a = np.array([1,2]) b = np.array([3,4]) a * b @@ -47,7 +47,7 @@ a * b Out[3]: -``` +```py array([3, 8]) ``` @@ -55,14 +55,14 @@ array([3, 8]) In [4]: -``` +```py np.multiply(a, b) ``` Out[4]: -``` +```py array([3, 8]) ``` @@ -70,27 +70,27 @@ array([3, 8]) In [5]: -``` +```py np.multiply(a, b, a) ``` Out[5]: -``` +```py array([3, 8]) ``` In [6]: -``` +```py a ``` Out[6]: -``` +```py array([3, 8]) ``` @@ -119,7 +119,7 @@ array([3, 8]) In [7]: -``` +```py a = np.array([[1,2,3,4], [2,3,4,5]]) b = np.array([[1,2,5,4], @@ -130,26 +130,26 @@ a == b Out[7]: -``` +```py array([[ True, True, False, True], [False, True, True, True]], dtype=bool) ``` 这意味着,如果我们在条件中要判断两个数组是否一样时,不能直接使用 -``` +```py if a == b: ``` 而要使用: -``` +```py if all(a==b): ``` 对于浮点数,由于存在精度问题,使用函数 `allclose` 会更好: -``` +```py if allclose(a,b): ``` @@ -157,7 +157,7 @@ if allclose(a,b): In [8]: -``` +```py a = np.array([0,1,2]) b = np.array([0,10,0]) @@ -167,7 +167,7 @@ np.logical_and(a, b) Out[8]: -``` +```py array([False, True, False], dtype=bool) ``` @@ -177,7 +177,7 @@ array([False, True, False], dtype=bool) In [9]: -``` +```py a = np.array([1,2,4,8]) b = np.array([16,32,64,128]) @@ -187,7 +187,7 @@ a | b Out[9]: -``` +```py array([ 17, 34, 68, 136]) ``` @@ -195,7 +195,7 @@ array([ 17, 34, 68, 136]) In [10]: -``` +```py a = np.array([1,2,3,4], np.uint8) ~a @@ -203,7 +203,7 @@ a = np.array([1,2,3,4], np.uint8) Out[10]: -``` +```py array([254, 253, 252, 251], dtype=uint8) ``` @@ -211,14 +211,14 @@ array([254, 253, 252, 251], dtype=uint8) In [11]: -``` +```py a << 3 ``` Out[11]: -``` +```py array([ 8, 16, 24, 32], dtype=uint8) ``` @@ -226,7 +226,7 @@ array([ 8, 16, 24, 32], dtype=uint8) In [12]: -``` +```py a = np.array([1,2,4,8]) b = np.array([16,32,64,128]) @@ -236,6 +236,6 @@ b = np.array([16,32,64,128]) Out[12]: -``` +```py array([False, False, True, False], dtype=bool) ``` \ No newline at end of file diff --git a/docs/da/044.md b/docs/da/044.md index 748a3f3e4..b260eaf02 100644 --- a/docs/da/044.md +++ b/docs/da/044.md @@ -6,14 +6,14 @@ In [1]: -``` +```py import numpy as np ``` In [2]: -``` +```py a = np.array([0,1,2]) b = np.array([2,3,4]) @@ -23,7 +23,7 @@ np.add(a, b) Out[2]: -``` +```py array([2, 4, 6]) ``` @@ -31,14 +31,14 @@ array([2, 4, 6]) In [3]: -``` +```py dir(np.add) ``` Out[3]: -``` +```py ['__call__', '__class__', '__delattr__', @@ -76,7 +76,7 @@ Out[3]: ## reduce 方法 -``` +```py op.reduce(a) ``` @@ -86,7 +86,7 @@ add 作用到一维数组上相当于求和: $$ \begin{align} y & = add.recuce(a) \\ & = a[0] + a[1] + ... + a[N-1] \\ & = \sum_{n=0}^{N-1} a[n] \end{align} $$In [4]: -``` +```py a = np.array([1,2,3,4]) np.add.reduce(a) @@ -95,7 +95,7 @@ np.add.reduce(a) Out[4]: -``` +```py 10 ``` @@ -103,7 +103,7 @@ Out[4]: In [5]: -``` +```py a = np.array([[1,2,3],[4,5,6]]) np.add.reduce(a) @@ -112,7 +112,7 @@ np.add.reduce(a) Out[5]: -``` +```py array([5, 7, 9]) ``` @@ -120,14 +120,14 @@ array([5, 7, 9]) In [6]: -``` +```py np.add.reduce(a, 1) ``` Out[6]: -``` +```py array([ 6, 15]) ``` @@ -135,7 +135,7 @@ array([ 6, 15]) In [7]: -``` +```py a = np.array(['ab', 'cd', 'ef'], np.object) np.add.reduce(a) @@ -144,7 +144,7 @@ np.add.reduce(a) Out[7]: -``` +```py 'abcdef' ``` @@ -152,7 +152,7 @@ Out[7]: In [8]: -``` +```py a = np.array([1,1,0,1]) np.logical_and.reduce(a) @@ -161,26 +161,26 @@ np.logical_and.reduce(a) Out[8]: -``` +```py False ``` In [9]: -``` +```py np.logical_or.reduce(a) ``` Out[9]: -``` +```py True ``` ## accumulate 方法 -``` +```py op.accumulate(a) ``` @@ -192,7 +192,7 @@ $$ \begin{align} y & = add.accumulate(a) \\ & = \left[\sum_{n=0}^{0} a[n], \sum_ In [10]: -``` +```py a = np.array([1,2,3,4]) np.add.accumulate(a) @@ -201,13 +201,13 @@ np.add.accumulate(a) Out[10]: -``` +```py array([ 1, 3, 6, 10]) ``` In [11]: -``` +```py a = np.array(['ab', 'cd', 'ef'], np.object) np.add.accumulate(a) @@ -216,13 +216,13 @@ np.add.accumulate(a) Out[11]: -``` +```py array(['ab', 'abcd', 'abcdef'], dtype=object) ``` In [12]: -``` +```py a = np.array([1,1,0,1]) np.logical_and.accumulate(a) @@ -231,26 +231,26 @@ np.logical_and.accumulate(a) Out[12]: -``` +```py array([ True, True, False, False], dtype=bool) ``` In [13]: -``` +```py np.logical_or.accumulate(a) ``` Out[13]: -``` +```py array([ True, True, True, True], dtype=bool) ``` ## reduceat 方法 -``` +```py op.reduceat(a, indices) ``` @@ -258,7 +258,7 @@ op.reduceat(a, indices) $$ \begin{align} y & = add.reduceat(a, indices) \\ & = \left[\sum_{n=indice[0]}^{indice[1]-1} a[n], \sum_{n=indice[1]}^{indice[2]-1} a[n], ..., \sum_{n=indice[-1]}^{N-1} a[n]\right] \end{align} $$In [14]: -``` +```py a = np.array([0, 10, 20, 30, 40, 50]) indices = np.array([1,4]) @@ -268,7 +268,7 @@ np.add.reduceat(a, indices) Out[14]: -``` +```py array([60, 90]) ``` @@ -276,7 +276,7 @@ array([60, 90]) ## outer 方法 -``` +```py op.outer(a, b) ``` @@ -284,7 +284,7 @@ op.outer(a, b) In [15]: -``` +```py a = np.array([0,1]) b = np.array([1,2,3]) @@ -294,7 +294,7 @@ np.add.outer(a, b) Out[15]: -``` +```py array([[1, 2, 3], [2, 3, 4]]) ``` @@ -303,14 +303,14 @@ array([[1, 2, 3], In [16]: -``` +```py np.add.outer(b, a) ``` Out[16]: -``` +```py array([[1, 2], [2, 3], [3, 4]]) diff --git a/docs/da/045.md b/docs/da/045.md index e9f7de772..71fcafd06 100644 --- a/docs/da/045.md +++ b/docs/da/045.md @@ -4,14 +4,14 @@ In [1]: -``` +```py import numpy as np ``` In [2]: -``` +```py control = np.array([[1,0,1], [2,1,0], [1,2,2]]) @@ -22,7 +22,7 @@ np.choose(control, [10, 11, 12]) Out[2]: -``` +```py array([[11, 10, 11], [12, 11, 10], [11, 12, 12]]) @@ -34,7 +34,7 @@ array([[11, 10, 11], In [3]: -``` +```py i0 = np.array([[0,1,2], [3,4,5], [6,7,8]]) @@ -51,7 +51,7 @@ np.choose(control, [i0, 10, i2]) Out[3]: -``` +```py array([[10, 1, 10], [23, 10, 5], [10, 27, 28]]) @@ -63,7 +63,7 @@ array([[10, 1, 10], In [4]: -``` +```py a = np.array([[ 0, 1, 2], [10,11,12], [20,21,22]]) @@ -74,7 +74,7 @@ a < 10 Out[4]: -``` +```py array([[ True, True, True], [False, False, False], [False, False, False]], dtype=bool) @@ -82,14 +82,14 @@ array([[ True, True, True], In [5]: -``` +```py np.choose(a < 10, (a, 10)) ``` Out[5]: -``` +```py array([[10, 10, 10], [10, 11, 12], [20, 21, 22]]) @@ -99,7 +99,7 @@ array([[10, 10, 10], In [6]: -``` +```py a = np.array([[ 0, 1, 2], [10,11,12], [20,21,22]]) @@ -114,7 +114,7 @@ choice Out[6]: -``` +```py array([[1, 1, 1], [0, 0, 0], [2, 2, 2]]) @@ -122,14 +122,14 @@ array([[1, 1, 1], In [7]: -``` +```py np.choose(choice, (a, 10, 15)) ``` Out[7]: -``` +```py array([[10, 10, 10], [10, 11, 12], [15, 15, 15]]) diff --git a/docs/da/046.md b/docs/da/046.md index ff2346cfe..24e0f363d 100644 --- a/docs/da/046.md +++ b/docs/da/046.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np ``` @@ -11,7 +11,7 @@ import numpy as np In [2]: -``` +```py a = np.array([[ 0, 0, 0], [10,10,10], [20,20,20], @@ -26,7 +26,7 @@ a + b Out[2]: -``` +```py array([[ 0, 1, 2], [10, 11, 12], [20, 21, 22], @@ -37,7 +37,7 @@ array([[ 0, 1, 2], In [3]: -``` +```py b = np.array([0,1,2]) a + b @@ -46,7 +46,7 @@ a + b Out[3]: -``` +```py array([[ 0, 1, 2], [10, 11, 12], [20, 21, 22], @@ -61,7 +61,7 @@ array([[ 0, 1, 2], In [4]: -``` +```py a = np.array([0,10,20,30]) a.shape = 4,1 a @@ -70,7 +70,7 @@ a Out[4]: -``` +```py array([[ 0], [10], [20], @@ -79,27 +79,27 @@ array([[ 0], In [5]: -``` +```py b ``` Out[5]: -``` +```py array([0, 1, 2]) ``` In [6]: -``` +```py a + b ``` Out[6]: -``` +```py array([[ 0, 1, 2], [10, 11, 12], [20, 21, 22], @@ -129,7 +129,7 @@ array([[ 0, 1, 2], In [7]: -``` +```py a = np.array([0,10,20,30]) a.shape @@ -137,31 +137,31 @@ a.shape Out[7]: -``` +```py (4L,) ``` In [8]: -``` +```py b.shape ``` Out[8]: -``` +```py (3L,) ``` In [9]: -``` +```py a + b ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -174,14 +174,14 @@ ValueError: operands could not be broadcast together with shapes (4,) (3,) In [10]: -``` +```py a[:, np.newaxis] + b ``` Out[10]: -``` +```py array([[ 0, 1, 2], [10, 11, 12], [20, 21, 22], @@ -192,41 +192,41 @@ array([[ 0, 1, 2], In [11]: -``` +```py x = np.linspace(-.5,.5, 21) ``` In [12]: -``` +```py y = x[:, np.newaxis] ``` In [13]: -``` +```py x.shape ``` Out[13]: -``` +```py (21L,) ``` In [14]: -``` +```py y.shape ``` Out[14]: -``` +```py (21L, 1L) ``` @@ -234,14 +234,14 @@ Out[14]: In [15]: -``` +```py radius = np.sqrt(x ** 2 + y ** 2) ``` In [16]: -``` +```py import matplotlib.pyplot as plt %matplotlib inline @@ -251,7 +251,7 @@ plt.imshow(radius) Out[16]: -``` +```py ``` diff --git a/docs/da/047.md b/docs/da/047.md index 58ae77bae..e1af16945 100644 --- a/docs/da/047.md +++ b/docs/da/047.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np ``` @@ -15,14 +15,14 @@ import numpy as np In [2]: -``` +```py %%writefile myfile.txt 2.1 2.3 3.2 1.3 3.1 6.1 3.1 4.2 2.3 1.8 ``` -``` +```py Writing myfile.txt ``` @@ -31,7 +31,7 @@ Writing myfile.txt In [3]: -``` +```py data = [] with open('myfile.txt') as f: @@ -47,14 +47,14 @@ data = np.array(data) In [4]: -``` +```py data ``` Out[4]: -``` +```py array([[ 2.1, 2.3, 3.2, 1.3, 3.1], [ 6.1, 3.1, 4.2, 2.3, 1.8]]) ``` @@ -63,7 +63,7 @@ array([[ 2.1, 2.3, 3.2, 1.3, 3.1], In [5]: -``` +```py data = np.loadtxt('myfile.txt') data @@ -71,7 +71,7 @@ data Out[5]: -``` +```py array([[ 2.1, 2.3, 3.2, 1.3, 3.1], [ 6.1, 3.1, 4.2, 2.3, 1.8]]) ``` @@ -80,14 +80,14 @@ array([[ 2.1, 2.3, 3.2, 1.3, 3.1], In [6]: -``` +```py %%writefile myfile.txt 2.1, 2.3, 3.2, 1.3, 3.1 6.1, 3.1, 4.2, 2.3, 1.8 ``` -``` +```py Overwriting myfile.txt ``` @@ -98,7 +98,7 @@ Overwriting myfile.txt In [7]: -``` +```py data = np.loadtxt('myfile.txt', delimiter=',') data @@ -106,14 +106,14 @@ data Out[7]: -``` +```py array([[ 2.1, 2.3, 3.2, 1.3, 3.1], [ 6.1, 3.1, 4.2, 2.3, 1.8]]) ``` ### loadtxt 函数 -``` +```py loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, @@ -126,7 +126,7 @@ loadtxt(fname, dtype=, In [8]: -``` +```py %%writefile myfile.txt X Y Z MAG ANG 2.1 2.3 3.2 1.3 3.1 @@ -134,28 +134,28 @@ X Y Z MAG ANG ``` -``` +```py Overwriting myfile.txt ``` In [9]: -``` +```py np.loadtxt('myfile.txt', skiprows=1) ``` Out[9]: -``` +```py array([[ 2.1, 2.3, 3.2, 1.3, 3.1], [ 6.1, 3.1, 4.2, 2.3, 1.8]]) ``` 此外,有一个功能更为全面的 `genfromtxt` 函数,能处理更多的情况,但相应的速度和效率会慢一些。 -``` +```py genfromtxt(fname, dtype=, comments='#', delimiter=None, skiprows=0, skip_header=0, skip_footer=0, converters=None, missing='', missing_values=None, filling_values=None, usecols=None, @@ -170,7 +170,7 @@ genfromtxt(fname, dtype=, comments='#', delimiter=None, In [10]: -``` +```py %%writefile myfile.txt -- BEGINNING OF THE FILE % Day, Month, Year, Skip, Power @@ -180,14 +180,14 @@ In [10]: ``` -``` +```py Overwriting myfile.txt ``` In [11]: -``` +```py data = np.loadtxt('myfile.txt', skiprows=1, #忽略第一行 dtype=np.int, #数组类型 @@ -201,7 +201,7 @@ data Out[11]: -``` +```py array([[ 1, 1, 2000, 13], [ 4, 1, 2000, 55]]) ``` @@ -210,14 +210,14 @@ array([[ 1, 1, 2000, 13], In [12]: -``` +```py %%writefile myfile.txt 2010-01-01 2.3 3.2 2011-01-01 6.1 3.1 ``` -``` +```py Overwriting myfile.txt ``` @@ -226,7 +226,7 @@ Overwriting myfile.txt In [13]: -``` +```py import datetime def date_converter(s): @@ -244,7 +244,7 @@ data Out[13]: -``` +```py array([[datetime.datetime(2010, 1, 1, 0, 0), 2.3, 3.2], [datetime.datetime(2011, 1, 1, 0, 0), 6.1, 3.1]], dtype=object) ``` @@ -253,7 +253,7 @@ array([[datetime.datetime(2010, 1, 1, 0, 0), 2.3, 3.2], In [14]: -``` +```py import os os.remove('myfile.txt') @@ -285,7 +285,7 @@ os.remove('myfile.txt') In [15]: -``` +```py data = np.array([[1,2], [3,4]]) @@ -295,14 +295,14 @@ np.savetxt('out.txt', data) In [16]: -``` +```py with open('out.txt') as f: for line in f: print line, ``` -``` +```py 1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00 4.000000000000000000e+00 @@ -312,7 +312,7 @@ with open('out.txt') as f: In [17]: -``` +```py data = np.array([[1,2], [3,4]]) @@ -322,14 +322,14 @@ np.savetxt('out.txt', data, fmt="%d") #保存为整数 In [18]: -``` +```py with open('out.txt') as f: for line in f: print line, ``` -``` +```py 1 2 3 4 @@ -339,7 +339,7 @@ with open('out.txt') as f: In [19]: -``` +```py data = np.array([[1,2], [3,4]]) @@ -349,14 +349,14 @@ np.savetxt('out.txt', data, fmt="%.2f", delimiter=',') #保存为2位小数的 In [20]: -``` +```py with open('out.txt') as f: for line in f: print line, ``` -``` +```py 1.00,2.00 3.00,4.00 @@ -366,7 +366,7 @@ with open('out.txt') as f: In [21]: -``` +```py data = np.array([[1+1j,2], [3,4]]) @@ -376,14 +376,14 @@ np.savetxt('out.txt', data, fmt="%.2f", delimiter=',') #保存为2位小数的 In [22]: -``` +```py with open('out.txt') as f: for line in f: print line, ``` -``` +```py (1.00+1.00j), (2.00+0.00j) (3.00+0.00j), (4.00+0.00j) @@ -391,7 +391,7 @@ with open('out.txt') as f: 更多参数: -``` +```py savetxt(fname, X, fmt='%.18e', @@ -406,7 +406,7 @@ savetxt(fname, In [23]: -``` +```py import os os.remove('out.txt') @@ -432,7 +432,7 @@ os.remove('out.txt') In [24]: -``` +```py a = np.array([[1.0,2.0], [3.0,4.0]]) fname = 'afile.npy' @@ -442,7 +442,7 @@ np.save(fname, a) In [25]: -``` +```py aa = np.load(fname) aa @@ -450,7 +450,7 @@ aa Out[25]: -``` +```py array([[ 1., 2.], [ 3., 4.]]) ``` @@ -459,7 +459,7 @@ array([[ 1., 2.], In [26]: -``` +```py import os os.remove('afile.npy') @@ -469,7 +469,7 @@ os.remove('afile.npy') In [27]: -``` +```py a = np.arange(10000.) ``` @@ -478,7 +478,7 @@ a = np.arange(10000.) In [28]: -``` +```py np.savetxt('a.txt', a) ``` @@ -487,7 +487,7 @@ np.savetxt('a.txt', a) In [29]: -``` +```py import os os.stat('a.txt').st_size @@ -495,7 +495,7 @@ os.stat('a.txt').st_size Out[29]: -``` +```py 260000L ``` @@ -503,7 +503,7 @@ Out[29]: In [30]: -``` +```py np.save('a.npy', a) ``` @@ -512,14 +512,14 @@ np.save('a.npy', a) In [31]: -``` +```py os.stat('a.npy').st_size ``` Out[31]: -``` +```py 80080L ``` @@ -527,7 +527,7 @@ Out[31]: In [32]: -``` +```py os.remove('a.npy') os.remove('a.txt') @@ -539,7 +539,7 @@ os.remove('a.txt') In [33]: -``` +```py a = np.array([[1.0,2.0], [3.0,4.0]]) b = np.arange(1000) @@ -550,7 +550,7 @@ b = np.arange(1000) In [34]: -``` +```py np.savez('data.npz', a=a, b=b) ``` @@ -559,12 +559,12 @@ np.savez('data.npz', a=a, b=b) In [35]: -``` +```py !unzip -l data.npz ``` -``` +```py Archive: data.npz Length Date Time Name --------- ---------- ----- ---- @@ -579,7 +579,7 @@ Archive: data.npz In [36]: -``` +```py data = np.load('data.npz') ``` @@ -588,41 +588,41 @@ data = np.load('data.npz') In [37]: -``` +```py data.keys() ``` Out[37]: -``` +```py ['a', 'b'] ``` In [38]: -``` +```py data['a'] ``` Out[38]: -``` +```py array([[ 1., 2.], [ 3., 4.]]) ``` In [39]: -``` +```py data['b'].shape ``` Out[39]: -``` +```py (1000L,) ``` @@ -630,7 +630,7 @@ Out[39]: In [40]: -``` +```py # 要先删除 data,否则删除时会报错 del data @@ -644,7 +644,7 @@ os.remove('data.npz') In [41]: -``` +```py a = np.arange(20000.) ``` @@ -653,7 +653,7 @@ a = np.arange(20000.) In [42]: -``` +```py np.savez('a.npz', a=a) os.stat('a.npz').st_size @@ -661,7 +661,7 @@ os.stat('a.npz').st_size Out[42]: -``` +```py 160188L ``` @@ -669,7 +669,7 @@ Out[42]: In [43]: -``` +```py np.savez_compressed('a2.npz', a=a) os.stat('a2.npz').st_size @@ -677,7 +677,7 @@ os.stat('a2.npz').st_size Out[43]: -``` +```py 26885L ``` @@ -687,7 +687,7 @@ Out[43]: In [44]: -``` +```py a = np.random.rand(20000.) ``` @@ -696,7 +696,7 @@ a = np.random.rand(20000.) In [45]: -``` +```py np.savez('a.npz', a=a) os.stat('a.npz').st_size @@ -704,7 +704,7 @@ os.stat('a.npz').st_size Out[45]: -``` +```py 160188L ``` @@ -712,7 +712,7 @@ Out[45]: In [46]: -``` +```py np.savez_compressed('a2.npz', a=a) os.stat('a2.npz').st_size @@ -720,7 +720,7 @@ os.stat('a2.npz').st_size Out[46]: -``` +```py 151105L ``` @@ -728,7 +728,7 @@ Out[46]: In [47]: -``` +```py os.remove('a.npz') os.remove('a2.npz') diff --git a/docs/da/048.md b/docs/da/048.md index c6abd534f..da3310a65 100644 --- a/docs/da/048.md +++ b/docs/da/048.md @@ -12,7 +12,7 @@ In [1]: -``` +```py import numpy as np ``` @@ -25,7 +25,7 @@ import numpy as np In [2]: -``` +```py a = np.array([1.0,2.0,3.0,4.0], np.float32) ``` @@ -34,14 +34,14 @@ a = np.array([1.0,2.0,3.0,4.0], np.float32) In [3]: -``` +```py a.view(np.complex64) ``` Out[3]: -``` +```py array([ 1.+2.j, 3.+4.j], dtype=complex64) ``` @@ -63,21 +63,21 @@ array([ 1.+2.j, 3.+4.j], dtype=complex64) In [4]: -``` +```py my_dtype = np.dtype([('mass', 'float32'), ('vol', 'float32')]) ``` In [5]: -``` +```py a.view(my_dtype) ``` Out[5]: -``` +```py array([(1.0, 2.0), (3.0, 4.0)], dtype=[('mass', ' @@ -106,7 +106,7 @@ print type(a) In [3]: -``` +```py a = numpy.matlib.ones(7) print a.shape @@ -114,7 +114,7 @@ print type(a) ``` -``` +```py (1L, 7L) @@ -124,7 +124,7 @@ print type(a) In [4]: -``` +```py a = numpy.array([1,2,3]) b = numpy.mat(a) @@ -133,7 +133,7 @@ print type(b) ``` -``` +```py ``` @@ -142,13 +142,13 @@ print type(b) In [5]: -``` +```py a = numpy.random.rand(10) print a ``` -``` +```py [ 0.66007267 0.34794294 0.5040946 0.65044648 0.74763248 0.42486999 0.90922612 0.69071747 0.33541076 0.08570178] @@ -160,7 +160,7 @@ print a In [6]: -``` +```py from numpy import * import scipy.linalg diff --git a/docs/da/053.md b/docs/da/053.md index e5a281992..54ea33024 100644 --- a/docs/da/053.md +++ b/docs/da/053.md @@ -40,7 +40,7 @@ In [1]: -``` +```py import numpy as np import scipy as sp import matplotlib as mpl @@ -52,7 +52,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py from scipy import linalg, optimize ``` @@ -63,12 +63,12 @@ from scipy import linalg, optimize In [3]: -``` +```py np.info(optimize.fmin) ``` -``` +```py fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, full_output=0, disp=1, retall=0, callback=None) @@ -154,12 +154,12 @@ References In [4]: -``` +```py np.lookfor("resize array") ``` -``` +```py Search results for 'resize array' --------------------------------- numpy.chararray.resize @@ -183,12 +183,12 @@ numpy.ma.mvoid.resize In [5]: -``` +```py np.lookfor("remove path", module="os") ``` -``` +```py Search results for 'remove path' -------------------------------- os.removedirs diff --git a/docs/da/054.md b/docs/da/054.md index 49afd1131..a08369cc4 100644 --- a/docs/da/054.md +++ b/docs/da/054.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np import matplotlib.pyplot as plt %matplotlib inline @@ -13,7 +13,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py np.set_printoptions(precision=2, suppress=True) ``` @@ -22,7 +22,7 @@ np.set_printoptions(precision=2, suppress=True) In [3]: -``` +```py data = np.genfromtxt("JANAF_CH4.txt", delimiter="\t", # TAB 分隔 skiprows=1, # 忽略首行 @@ -36,14 +36,14 @@ data = np.genfromtxt("JANAF_CH4.txt", In [4]: -``` +```py for row in data[:7]: print "{}\t{}".format(row['TK'], row['Cp']) print "...\t..." ``` -``` +```py 0.0 0.0 100.0 33.258 200.0 33.473 @@ -59,7 +59,7 @@ print "...\t..." In [5]: -``` +```py p = plt.plot(data['TK'], data['Cp'], 'kx') t = plt.title("JANAF data for Methane $CH_4$") a = plt.axis([0, 6000, 30, 120]) @@ -250,20 +250,20 @@ ZmaWKwcWMzPLlQOLmZnl6n8BKYzjzfpoiFsAAAAASUVORK5CYII= 先导入一维插值函数 `interp1d`: -``` +```py interp1d(x, y) ``` In [6]: -``` +```py from scipy.interpolate import interp1d ``` In [7]: -``` +```py ch4_cp = interp1d(data['TK'], data['Cp']) ``` @@ -274,14 +274,14 @@ ch4_cp = interp1d(data['TK'], data['Cp']) In [8]: -``` +```py ch4_cp(382.2) ``` Out[8]: -``` +```py array(39.565144000000004) ``` @@ -289,14 +289,14 @@ array(39.565144000000004) In [9]: -``` +```py ch4_cp([32.2,323.2]) ``` Out[9]: -``` +```py array([ 10.71, 36.71]) ``` @@ -304,12 +304,12 @@ array([ 10.71, 36.71]) In [10]: -``` +```py ch4_cp(8752) ``` -``` +```py --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () @@ -342,7 +342,7 @@ ValueError: A value in x_new is above the interpolation range. In [11]: -``` +```py ch4_cp = interp1d(data['TK'], data['Cp'], bounds_error=False) @@ -352,14 +352,14 @@ ch4_cp = interp1d(data['TK'], data['Cp'], In [12]: -``` +```py ch4_cp(8752) ``` Out[12]: -``` +```py array(nan) ``` @@ -367,7 +367,7 @@ array(nan) In [13]: -``` +```py ch4_cp = interp1d(data['TK'], data['Cp'], bounds_error=False, fill_value=-999.25) @@ -375,14 +375,14 @@ ch4_cp = interp1d(data['TK'], data['Cp'], In [14]: -``` +```py ch4_cp(8752) ``` Out[14]: -``` +```py array(-999.25) ``` @@ -399,7 +399,7 @@ array(-999.25) In [15]: -``` +```py T = np.arange(100,355,5) plt.plot(T, ch4_cp(T), "+k") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -514,7 +514,7 @@ SSViqEtSiRjqklQihroklcj/A8xgms4BB0nlAAAAAElFTkSuQmCC In [16]: -``` +```py cp_ch4 = interp1d(data['TK'], data['Cp'], kind="nearest") p = plt.plot(T, cp_ch4(T), "k+") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -612,7 +612,7 @@ iKEuSQUx1CWpIIa6JBXk/wGLsxItFlRd2gAAAABJRU5ErkJggg== In [17]: -``` +```py cp_ch4 = interp1d(data['TK'], data['Cp'], kind="zero") p = plt.plot(T, cp_ch4(T), "k+") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -707,7 +707,7 @@ xFCXpIIY6pJUEENdkgpiqEtSQf4fzDOJu6Be93AAAAAASUVORK5CYII= In [18]: -``` +```py cp_ch4 = interp1d(data['TK'], data['Cp'], kind="quadratic") p = plt.plot(T, cp_ch4(T), "k+") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -810,7 +810,7 @@ qEtShRjqklQh/w+L/6C1jqXsbQAAAABJRU5ErkJggg== In [19]: -``` +```py cp_ch4 = interp1d(data['TK'], data['Cp'], kind="cubic") p = plt.plot(T, cp_ch4(T), "k+") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -916,7 +916,7 @@ AElFTkSuQmCC In [20]: -``` +```py cp_ch4 = interp1d(data['TK'], data['Cp'], kind=4) p = plt.plot(T, cp_ch4(T), "k+") p = plt.plot(data['TK'][1:7], data['Cp'][1:7], 'ro', markersize=8) @@ -1025,7 +1025,7 @@ AABJRU5ErkJggg== In [21]: -``` +```py from scipy.interpolate import interp2d, interpnd ``` @@ -1042,7 +1042,7 @@ from scipy.interpolate import interp2d, interpnd $$\Phi(x,c) = \Phi(\|x-c\|)$$In [22]: -``` +```py x = np.linspace(-3,3,100) ``` @@ -1053,7 +1053,7 @@ x = np.linspace(-3,3,100) In [23]: -``` +```py plt.plot(x, np.exp(-1 * x **2)) t = plt.title("Gaussian") @@ -1230,7 +1230,7 @@ wKmQi4gUOBVyEZEC9/8BloffFHVXiTcAAAAASUVORK5CYII= In [24]: -``` +```py plt.plot(x, np.sqrt(1 + x **2)) t = plt.title("Multiquadric") @@ -1408,7 +1408,7 @@ JJwSuYhIwv0/gG56R7Cwt98AAAAASUVORK5CYII= In [25]: -``` +```py plt.plot(x, 1. / np.sqrt(1 + x **2)) t = plt.title("Inverse Multiquadric") @@ -1619,7 +1619,7 @@ $$ f(x) = \sum_j n_j \Phi(\|x-x_j\|) $$ In [26]: -``` +```py from scipy.interpolate.rbf import Rbf ``` @@ -1628,7 +1628,7 @@ from scipy.interpolate.rbf import Rbf In [27]: -``` +```py cp_rbf = Rbf(data['TK'], data['Cp'], function = "multiquadric") plt.plot(data['TK'], data['Cp'], 'k+') p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-') @@ -1793,7 +1793,7 @@ SJJR8IuIJBkFv4hIklHwi4gkGQW/iEiSUfCLiCSZ/wfUE99TkRdDtgAAAABJRU5ErkJggg== In [28]: -``` +```py cp_rbf = Rbf(data['TK'], data['Cp'], function = "gaussian") plt.plot(data['TK'], data['Cp'], 'k+') p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-') @@ -1986,7 +1986,7 @@ wgAAAABJRU5ErkJggg== In [29]: -``` +```py cp_rbf = Rbf(data['TK'], data['Cp'], function = "inverse_multiquadric") plt.plot(data['TK'], data['Cp'], 'k+') p = plt.plot(data['TK'], cp_rbf(data['TK']), 'r-') @@ -2153,7 +2153,7 @@ iCQZBb+ISJJR8IuIJJn/D8ptq7/3lHsDAAAAAElFTkSuQmCC In [30]: -``` +```py from mpl_toolkits.mplot3d import Axes3D ``` @@ -2162,7 +2162,7 @@ from mpl_toolkits.mplot3d import Axes3D In [31]: -``` +```py x, y = np.mgrid[-np.pi/2:np.pi/2:5j, -np.pi/2:np.pi/2:5j] z = np.cos(np.sqrt(x**2 + y**2)) @@ -2170,7 +2170,7 @@ z = np.cos(np.sqrt(x**2 + y**2)) In [32]: -``` +```py fig = plt.figure(figsize=(12,6)) ax = fig.gca(projection="3d") ax.scatter(x,y,z) @@ -2179,7 +2179,7 @@ ax.scatter(x,y,z) Out[32]: -``` +```py ``` @@ -2921,14 +2921,14 @@ IbFKEARBEARBqJb/D6nRM2cdX17QAAAAAElFTkSuQmCC In [33]: -``` +```py zz = Rbf(x, y, z) ``` In [34]: -``` +```py xx, yy = np.mgrid[-np.pi/2:np.pi/2:50j, -np.pi/2:np.pi/2:50j] fig = plt.figure(figsize=(12,6)) ax = fig.gca(projection="3d") @@ -2938,7 +2938,7 @@ ax.plot_surface(xx,yy,zz(xx,yy),rstride=1, cstride=1, cmap=plt.cm.jet) Out[34]: -``` +```py ``` diff --git a/docs/da/055.md b/docs/da/055.md index 2558d2ad0..df31d5c53 100644 --- a/docs/da/055.md +++ b/docs/da/055.md @@ -10,19 +10,19 @@ In [1]: -``` +```py %pylab inline ``` -``` +```py Populating the interactive namespace from numpy and matplotlib ``` In [2]: -``` +```py heights = array([1.46, 1.79, 2.01, 1.75, 1.56, 1.69, 1.88, 1.76, 1.88, 1.78]) ``` @@ -31,7 +31,7 @@ heights = array([1.46, 1.79, 2.01, 1.75, 1.56, 1.69, 1.88, 1.76, 1.88, 1.78]) In [3]: -``` +```py print 'mean, ', heights.mean() print 'min, ', heights.min() print 'max, ', heights.max() @@ -39,7 +39,7 @@ print 'standard deviation, ', heights.std() ``` -``` +```py mean, 1.756 min, 1.46 max, 2.01 @@ -51,7 +51,7 @@ standard deviation, 0.150811140172 In [4]: -``` +```py import scipy.stats.stats as st ``` @@ -60,7 +60,7 @@ import scipy.stats.stats as st In [5]: -``` +```py print 'median, ', st.nanmedian(heights) # 忽略nan值之后的中位数 print 'mode, ', st.mode(heights) # 众数及其出现次数 print 'skewness, ', st.skew(heights) # 偏度 @@ -69,7 +69,7 @@ print 'and so many more...' ``` -``` +```py median, 1.77 mode, (array([ 1.88]), array([ 2.])) skewness, -0.393524456473 @@ -105,7 +105,7 @@ and so many more... In [6]: -``` +```py from scipy.stats import norm ``` @@ -121,7 +121,7 @@ from scipy.stats import norm In [7]: -``` +```py x_norm = norm.rvs(size=500) type(x_norm) @@ -129,7 +129,7 @@ type(x_norm) Out[7]: -``` +```py numpy.ndarray ``` @@ -137,14 +137,14 @@ numpy.ndarray In [8]: -``` +```py h = hist(x_norm) print 'counts, ', h[0] print 'bin centers', h[1] ``` -``` +```py counts, [ 7\. 21\. 42\. 97\. 120\. 91\. 64\. 38\. 17\. 3.] bin centers [-2.68067801 -2.13266147 -1.58464494 -1.0366284 -0.48861186 0.05940467 0.60742121 1.15543774 1.70345428 2.25147082 2.79948735] @@ -230,7 +230,7 @@ khphoEtSI/4P1qxllG6H6EYAAAAASUVORK5CYII= In [9]: -``` +```py h = hist(x_norm, normed=True, bins=20) ``` @@ -316,7 +316,7 @@ AAAASUVORK5CYII= In [10]: -``` +```py x_mean, x_std = norm.fit(x_norm) print 'mean, ', x_mean @@ -324,7 +324,7 @@ print 'x_std, ', x_std ``` -``` +```py mean, -0.0426135499965 x_std, 0.950754110144 @@ -334,7 +334,7 @@ x_std, 0.950754110144 In [11]: -``` +```py h = hist(x_norm, normed=True, bins=20) x = linspace(-3,3,50) @@ -512,7 +512,7 @@ KZGLiETc/wfoqVYxTpVDEwAAAABJRU5ErkJggg== In [12]: -``` +```py from scipy.integrate import trapz ``` @@ -521,7 +521,7 @@ from scipy.integrate import trapz In [13]: -``` +```py x1 = linspace(-2,2,108) p = trapz(norm.pdf(x1), x1) print '{:.2%} of the values lie between -2 and 2'.format(p) @@ -531,14 +531,14 @@ plot(x, norm.pdf(x), 'k-') ``` -``` +```py 95.45% of the values lie between -2 and 2 ``` Out[13]: -``` +```py [] ``` @@ -751,7 +751,7 @@ FXhjjIlSVuCNMSZK/T8+DStxCxquAQAAAABJRU5ErkJggg== In [14]: -``` +```py p = plot(x, norm.pdf(x, loc=0, scale=1)) p = plot(x, norm.pdf(x, loc=0.5, scale=2)) p = plot(x, norm.pdf(x, loc=-0.5, scale=.5)) @@ -1020,7 +1020,7 @@ AAAAAElFTkSuQmCC In [15]: -``` +```py p = plot(x, norm(loc=0, scale=1).pdf(x)) p = plot(x, norm(loc=0.5, scale=2).pdf(x)) p = plot(x, norm(loc=-0.5, scale=.5).pdf(x)) @@ -1289,7 +1289,7 @@ AAAAAElFTkSuQmCC In [16]: -``` +```py from scipy.stats import lognorm, t, dweibull ``` @@ -1300,7 +1300,7 @@ from scipy.stats import lognorm, t, dweibull In [17]: -``` +```py x = linspace(0.01, 3, 100) plot(x, lognorm.pdf(x, 1), label='s=1') @@ -1313,7 +1313,7 @@ legend() Out[17]: -``` +```py ``` @@ -1543,7 +1543,7 @@ OolJKaWikN7KRimlopAGd6WUikIa3JVSKgppcFdKqSikwV0ppaKQBnellIpCGtyVUioKaXBXSqko In [18]: -``` +```py x = linspace(0.01, 3, 100) plot(x, dweibull.pdf(x, 1), label='s=1, constant failure rate') @@ -1556,7 +1556,7 @@ legend() Out[18]: -``` +```py ``` @@ -1881,7 +1881,7 @@ AAAAAElFTkSuQmCC In [19]: -``` +```py x = linspace(-3, 3, 100) plot(x, t.pdf(x, 1), label='df=1') @@ -1895,7 +1895,7 @@ legend() Out[19]: -``` +```py ``` @@ -2312,7 +2312,7 @@ WVYNZRO8ZVlWDWUTvGVZVg1lE7xlWVYN9f98mteu43HACgAAAABJRU5ErkJggg== In [20]: -``` +```py from scipy.stats import binom, poisson, randint ``` @@ -2323,7 +2323,7 @@ from scipy.stats import binom, poisson, randint In [21]: -``` +```py high = 10 low = -10 @@ -2423,7 +2423,7 @@ khpg2EtSAwx7SWqAYS9JDTDsJakBhr0kNcCwl6QG/H9rCjVZAnNsTgAAAABJRU5ErkJggg== In [22]: -``` +```py num_trials = 60 x = arange(num_trials) @@ -2436,7 +2436,7 @@ legend() Out[22]: -``` +```py ``` @@ -2708,7 +2708,7 @@ aLJXSqk48P8B4O96y1bc/nYAAAAASUVORK5CYII= In [23]: -``` +```py x = arange(0,21) plot(x, poisson(1).pmf(x), 'o-', label=r'$\lambda$=1') @@ -2721,7 +2721,7 @@ legend() Out[23]: -``` +```py ``` @@ -3008,7 +3008,7 @@ gg== In [24]: -``` +```py from scipy.stats import rv_discrete ``` @@ -3017,7 +3017,7 @@ from scipy.stats import rv_discrete In [25]: -``` +```py xk = [1, 2, 3, 4, 5, 6] pk = [.3, .35, .25, .05, .025, .025] @@ -3027,7 +3027,7 @@ pk = [.3, .35, .25, .05, .025, .025] In [26]: -``` +```py loaded = rv_discrete(values=(xk, pk)) ``` @@ -3038,14 +3038,14 @@ loaded = rv_discrete(values=(xk, pk)) In [27]: -``` +```py loaded.rvs(size=2) ``` Out[27]: -``` +```py array([3, 1]) ``` @@ -3053,7 +3053,7 @@ array([3, 1]) In [28]: -``` +```py samples = loaded.rvs(size=100) bins = linspace(.5,6.5,7) @@ -3064,7 +3064,7 @@ stem(xk, loaded.pmf(xk), markerfmt='ro', linefmt='r-') Out[28]: -``` +```py ``` @@ -3187,7 +3187,7 @@ iXLAm5klygFvZpYoB7yZWaIc8GZmifp/J4pqDI9mKMcAAAAASUVORK5CYII= In [29]: -``` +```py from scipy.stats import norm from scipy.stats import ttest_ind, ttest_rel, ttest_1samp from scipy.stats import t @@ -3200,7 +3200,7 @@ from scipy.stats import t In [30]: -``` +```py n1 = norm(loc=0.3, scale=1.0) n2 = norm(loc=0, scale=1.0) @@ -3210,7 +3210,7 @@ n2 = norm(loc=0, scale=1.0) In [31]: -``` +```py n1_samples = n1.rvs(size=100) n2_samples = n2.rvs(size=100) @@ -3220,7 +3220,7 @@ n2_samples = n2.rvs(size=100) In [32]: -``` +```py samples = hstack((n1_samples, n2_samples)) ``` @@ -3229,7 +3229,7 @@ samples = hstack((n1_samples, n2_samples)) In [33]: -``` +```py loc, scale = norm.fit(samples) n = norm(loc=loc, scale=scale) @@ -3239,7 +3239,7 @@ n = norm(loc=loc, scale=scale) In [34]: -``` +```py x = linspace(-3,3,100) hist([samples, n1_samples, n2_samples], normed=True) @@ -3251,7 +3251,7 @@ plot(x, n2.pdf(x), 'r-') Out[34]: -``` +```py [] ``` @@ -3544,7 +3544,7 @@ IYRwcpLIhRDCyUkiF0IIJ/d/XdaGnd6OVMIAAAAASUVORK5CYII= In [35]: -``` +```py t_val, p = ttest_ind(n1_samples, n2_samples) print 't = {}'.format(t_val) @@ -3552,7 +3552,7 @@ print 'p-value = {}'.format(p) ``` -``` +```py t = 0.868384594123 p-value = 0.386235148899 @@ -3566,7 +3566,7 @@ p-value = 0.386235148899 In [36]: -``` +```py pop_size = 35 pre_treat = norm(loc=0, scale=1) @@ -3578,7 +3578,7 @@ n0 = pre_treat.rvs(size=pop_size) In [37]: -``` +```py effect = norm(loc=0.05, scale=0.2) eff = effect.rvs(size=pop_size) @@ -3590,7 +3590,7 @@ n1 = n0 + eff In [38]: -``` +```py loc, scale = norm.fit(n1) post_treat = norm(loc=loc, scale=scale) @@ -3600,7 +3600,7 @@ post_treat = norm(loc=loc, scale=scale) In [39]: -``` +```py fig = figure(figsize=(10,4)) ax1 = fig.add_subplot(1,2,1) @@ -3867,7 +3867,7 @@ SEBUWImIiIgERIWViIiISEBUWImIiIgE5P8B6WVRSESuXscAAAAASUVORK5CYII= In [40]: -``` +```py t_val, p = ttest_ind(n0, n1) print 't = {}'.format(t_val) @@ -3875,7 +3875,7 @@ print 'p-value = {}'.format(p) ``` -``` +```py t = -0.347904839913 p-value = 0.728986322039 @@ -3887,7 +3887,7 @@ p-value = 0.728986322039 In [41]: -``` +```py t_val, p = ttest_rel(n0, n1) print 't = {}'.format(t_val) @@ -3895,7 +3895,7 @@ print 'p-value = {}'.format(p) ``` -``` +```py t = -1.89564459709 p-value = 0.0665336223673 @@ -3909,7 +3909,7 @@ p-value = 0.0665336223673 In [42]: -``` +```py my_t = t(pop_size) # 传入参数为自由度,这里自由度为50 p = plot(x, my_t.pdf(x), 'b-') diff --git a/docs/da/056.md b/docs/da/056.md index 59bed5906..5d7eea676 100644 --- a/docs/da/056.md +++ b/docs/da/056.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt @@ -17,7 +17,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py from numpy import polyfit, poly1d ``` @@ -26,7 +26,7 @@ from numpy import polyfit, poly1d In [3]: -``` +```py x = np.linspace(-5, 5, 100) y = 4 * x + 1.5 noise_y = y + np.random.randn(y.shape[-1]) * 2.5 @@ -37,7 +37,7 @@ noise_y = y + np.random.randn(y.shape[-1]) * 2.5 In [4]: -``` +```py %matplotlib inline p = plt.plot(x, noise_y, 'rx') @@ -211,13 +211,13 @@ DpwbdZAmKImIJEytUzEiIlJhCuwiIgmjwC4ikjAK7CIiCaPALiKSMArsIiIJo8AuIpIwCuwiIgnz In [5]: -``` +```py coeff = polyfit(x, noise_y, 1) print coeff ``` -``` +```py [ 3.93921315 1.59379469] ``` @@ -228,7 +228,7 @@ print coeff In [6]: -``` +```py p = plt.plot(x, noise_y, 'rx') p = plt.plot(x, coeff[0] * x + coeff[1], 'k-') p = plt.plot(x, y, 'b--') @@ -434,7 +434,7 @@ rkJggg== In [7]: -``` +```py f = poly1d(coeff) p = plt.plot(x, noise_y, 'rx') p = plt.plot(x, f(x)) @@ -623,14 +623,14 @@ TbkUxv9z1wIPRzoeHwCXxNtIA5REREIm36kYERHJMgV2EZGQUWAXEQkZBXYRkZBRYBcRCRkFdhGR kFFgFxEJGQV2EZGQ+X/DyfQNy7jRVwAAAABJRU5ErkJggg== )In [8]: -``` +```py f ``` Out[8]: -``` +```py poly1d([ 3.93921315, 1.59379469]) ``` @@ -638,12 +638,12 @@ poly1d([ 3.93921315, 1.59379469]) In [9]: -``` +```py print f ``` -``` +```py 3.939 x + 1.594 @@ -653,12 +653,12 @@ print f In [10]: -``` +```py print f + 2 * f ** 2 ``` -``` +```py 2 31.03 x + 29.05 x + 6.674 @@ -670,7 +670,7 @@ print f + 2 * f ** 2 In [11]: -``` +```py x = np.linspace(-np.pi,np.pi,100) y = np.sin(x) @@ -680,7 +680,7 @@ y = np.sin(x) In [12]: -``` +```py y1 = poly1d(polyfit(x,y,1)) y3 = poly1d(polyfit(x,y,3)) y5 = poly1d(polyfit(x,y,5)) @@ -691,7 +691,7 @@ y9 = poly1d(polyfit(x,y,9)) In [13]: -``` +```py x = np.linspace(-3 * np.pi,3 * np.pi,100) p = plt.plot(x, np.sin(x), 'k') @@ -1137,7 +1137,7 @@ iBJ3hUKh0CFK3BUKhUKH/AdKQZTK2jwwogAAAABJRU5ErkJggg== In [14]: -``` +```py from scipy.linalg import lstsq from scipy.stats import linregress @@ -1145,7 +1145,7 @@ from scipy.stats import linregress In [15]: -``` +```py x = np.linspace(0,5,100) y = 0.5 * x + np.random.randn(x.shape[-1]) * 0.35 @@ -1155,7 +1155,7 @@ plt.plot(x,y,'x') Out[15]: -``` +```py [] ``` @@ -1309,7 +1309,7 @@ $$\left[ \begin{matrix} x_0^{N-1} & \dots & x_0 & 1 \\\ x_1^{N-1} & \dots & x_1 In [16]: -``` +```py X = np.hstack((x[:,np.newaxis], np.ones((x.shape[-1],1)))) X[1:5] @@ -1317,7 +1317,7 @@ X[1:5] Out[16]: -``` +```py array([[ 0.05050505, 1\. ], [ 0.1010101 , 1\. ], [ 0.15151515, 1\. ], @@ -1328,7 +1328,7 @@ array([[ 0.05050505, 1\. ], In [17]: -``` +```py C, resid, rank, s = lstsq(X, y) C, resid, rank, s @@ -1336,7 +1336,7 @@ C, resid, rank, s Out[17]: -``` +```py (array([ 0.50432002, 0.0415695 ]), 12.182942535066523, 2, @@ -1347,7 +1347,7 @@ Out[17]: In [18]: -``` +```py p = plt.plot(x, y, 'rx') p = plt.plot(x, C[0] * x + C[1], 'k--') print "sum squared residual = {:.3f}".format(resid) @@ -1356,7 +1356,7 @@ print "singular values of X = {}".format(s) ``` -``` +```py sum squared residual = 12.183 rank of the X matrix = 2 singular values of X = [ 30.23732043 4.82146667] @@ -1545,7 +1545,7 @@ TkSuQmCC In [19]: -``` +```py slope, intercept, r_value, p_value, stderr = linregress(x, y) slope, intercept @@ -1553,13 +1553,13 @@ slope, intercept Out[19]: -``` +```py (0.50432001884393252, 0.041569499438028901) ``` In [20]: -``` +```py p = plt.plot(x, y, 'rx') p = plt.plot(x, slope * x + intercept, 'k--') print "R-value = {:.3f}".format(r_value) @@ -1568,7 +1568,7 @@ print "Root mean squared error of the fit = {:.3f}".format(np.sqrt(stderr)) ``` -``` +```py R-value = 0.903 p-value (probability there is no correlation) = 8.225e-38 Root mean squared error of the fit = 0.156 @@ -1756,7 +1756,7 @@ gzwRkY8xyBMR+RiDPBGRjzHIExH5GIM8EZGPMcgTEfnY/we7I5NFwW+W8wAAAABJRU5ErkJggg== In [21]: -``` +```py from scipy.optimize import leastsq ``` @@ -1765,7 +1765,7 @@ from scipy.optimize import leastsq In [22]: -``` +```py def function(x, a , b, f, phi): """a function of x with four parameters""" result = a * np.exp(-b * np.sin(f * x + phi)) @@ -1777,7 +1777,7 @@ def function(x, a , b, f, phi): In [23]: -``` +```py x = np.linspace(0, 2 * np.pi, 50) actual_parameters = [3, 2, 1.25, np.pi / 4] y = function(x, *actual_parameters) @@ -1924,7 +1924,7 @@ LSKSMApuEZGEUXCLiCSMgltEJGH+Px9Ir5f410BLAAAAAElFTkSuQmCC In [24]: -``` +```py from scipy.stats import norm y_noisy = y + 0.8 * norm.rvs(size=len(x)) p = plt.plot(x, y, 'k-') @@ -2124,7 +2124,7 @@ AABJRU5ErkJggg== In [25]: -``` +```py def f_err(p, y, x): return y - function(x, *p) @@ -2134,7 +2134,7 @@ def f_err(p, y, x): In [26]: -``` +```py c, ret_val = leastsq(f_err, [1, 1, 1, 1], args=(y_noisy, x)) c, ret_val @@ -2142,7 +2142,7 @@ c, ret_val Out[26]: -``` +```py (array([ 3.03199715, 1.97689384, 1.30083191, 0.6393337 ]), 1) ``` @@ -2150,7 +2150,7 @@ Out[26]: In [27]: -``` +```py p = plt.plot(x, y_noisy, 'rx') p = plt.plot(x, function(x, *c), 'k--') @@ -2317,7 +2317,7 @@ A5MAAAAASUVORK5CYII= In [28]: -``` +```py from scipy.optimize import curve_fit ``` @@ -2326,21 +2326,21 @@ from scipy.optimize import curve_fit In [29]: -``` +```py p_est, err_est = curve_fit(function, x, y_noisy) ``` In [30]: -``` +```py print p_est p = plt.plot(x, y_noisy, "rx") p = plt.plot(x, function(x, *p_est), "k--") ``` -``` +```py [ 3.03199711 1.97689385 1.3008319 0.63933373] ``` @@ -2504,12 +2504,12 @@ A5MAAAAASUVORK5CYII= In [31]: -``` +```py print err_est ``` -``` +```py [[ 0.08483704 -0.02782318 0.00967093 -0.03029038] [-0.02782318 0.00933216 -0.00305158 0.00955794] [ 0.00967093 -0.00305158 0.0014972 -0.00468919] @@ -2521,14 +2521,14 @@ print err_est In [32]: -``` +```py print "normalized relative errors for each parameter" print " a\t b\t f\tphi" print np.sqrt(err_est.diagonal()) / p_est ``` -``` +```py normalized relative errors for each parameter a b f phi [ 0.09606473 0.0488661 0.02974528 0.19056043] diff --git a/docs/da/057.md b/docs/da/057.md index 5b00ddde4..1e699f8ec 100644 --- a/docs/da/057.md +++ b/docs/da/057.md @@ -4,13 +4,13 @@ In [1]: -``` +```py %pylab inline set_printoptions(precision=3, suppress=True) ``` -``` +```py Populating the interactive namespace from numpy and matplotlib ``` @@ -30,7 +30,7 @@ $d = 2 \frac{v_0^2}{g} \sin(\theta) \cos (\theta)$ In [2]: -``` +```py def dist(theta, v0): """calculate the distance travelled by a projectile launched at theta degrees with v0 (m/s) initial velocity. @@ -271,7 +271,7 @@ AAAASUVORK5CYII= In [3]: -``` +```py def neg_dist(theta, v0): return -1 * dist(theta, v0) @@ -281,14 +281,14 @@ def neg_dist(theta, v0): In [4]: -``` +```py from scipy.optimize import minimize result = minimize(neg_dist, 40, args=(1,)) print "optimal angle = {:.1f} degrees".format(result.x[0]) ``` -``` +```py optimal angle = 45.0 degrees ``` @@ -299,12 +299,12 @@ optimal angle = 45.0 degrees In [5]: -``` +```py print result ``` -``` +```py status: 0 success: True njev: 18 @@ -327,7 +327,7 @@ $f(x)=\sum\limits_{i=1}^{N-1}{100\left(x_{i+1}^2 - x_i\right) ^2 + \left(1-x_{i} In [6]: -``` +```py from scipy.optimize import rosen from mpl_toolkits.mplot3d import Axes3D @@ -337,7 +337,7 @@ from mpl_toolkits.mplot3d import Axes3D In [7]: -``` +```py x, y = meshgrid(np.linspace(-2,2,25), np.linspace(-0.5,3.5,25)) z = rosen([x,y]) @@ -347,7 +347,7 @@ z = rosen([x,y]) In [8]: -``` +```py fig = figure(figsize=(12,5.5)) ax = fig.gca(projection="3d") ax.azim = 70; ax.elev = 48 @@ -2354,14 +2354,14 @@ bxj8dmObAAAAAElFTkSuQmCC In [9]: -``` +```py x0 = [1.3, 1.6, -0.5, -1.8, 0.8] result = minimize(rosen, x0) print result.x ``` -``` +```py [ 1\. 1\. 1\. 1\. 1.] ``` @@ -2370,7 +2370,7 @@ print result.x In [10]: -``` +```py x0 = np.random.randn(10) result = minimize(rosen, x0) print x0 @@ -2378,7 +2378,7 @@ print result.x ``` -``` +```py [ 0.815 -2.086 0.297 1.079 -0.528 0.461 -0.13 -0.715 0.734 0.621] [-0.993 0.997 0.998 0.999 0.999 0.999 0.998 0.997 0.994 0.988] @@ -2396,12 +2396,12 @@ print result.x In [11]: -``` +```py info(minimize) ``` -``` +```py minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None) @@ -2699,7 +2699,7 @@ It should converge to the theoretical solution (1.4 ,1.7). In [12]: -``` +```py x0 = [-1.5, 4.5] xi = [x0] result = minimize(rosen, x0, callback=xi.append) @@ -2710,7 +2710,7 @@ print "in {} function evaluations.".format(result.nfev) ``` -``` +```py (37L, 2L) [ 1\. 1.] in 200 function evaluations. @@ -2721,7 +2721,7 @@ in 200 function evaluations. In [13]: -``` +```py x, y = meshgrid(np.linspace(-2.3,1.75,25), np.linspace(-0.5,4.5,25)) z = rosen([x,y]) fig = figure(figsize=(12,5.5)) @@ -4464,7 +4464,7 @@ $$J= \left[ \begin{matrix}\frac{\partial rosen}{\partial x_0} & \frac{\partial r In [14]: -``` +```py from scipy.optimize import rosen_der ``` @@ -4473,7 +4473,7 @@ from scipy.optimize import rosen_der In [15]: -``` +```py xi = [x0] result = minimize(rosen, x0, jac=rosen_der, callback=xi.append) xi = np.asarray(xi) @@ -4482,7 +4482,7 @@ print "in {} function evaluations and {} jacobian evaluations.".format(result.nf ``` -``` +```py (38L, 2L) in 49 function evaluations and 49 jacobian evaluations. @@ -4492,7 +4492,7 @@ in 49 function evaluations and 49 jacobian evaluations. In [16]: -``` +```py x, y = meshgrid(np.linspace(-2.3,1.75,25), np.linspace(-0.5,4.5,25)) z = rosen([x,y]) fig = figure(figsize=(12,5.5)) @@ -6227,7 +6227,7 @@ COGxJFgVQgghhBAe6/8D6bfN7+5DVO4AAAAASUVORK5CYII= In [17]: -``` +```py xi = [x0] result = minimize(rosen, x0, method="nelder-mead", callback = xi.append) xi = np.asarray(xi) @@ -6236,7 +6236,7 @@ print "Solved the Nelder-Mead Simplex method with {} function evaluations.".form ``` -``` +```py (120L, 2L) Solved the Nelder-Mead Simplex method with 226 function evaluations. @@ -6244,7 +6244,7 @@ Solved the Nelder-Mead Simplex method with 226 function evaluations. In [18]: -``` +```py x, y = meshgrid(np.linspace(-1.9,1.75,25), np.linspace(-0.5,4.5,25)) z = rosen([x,y]) fig = figure(figsize=(12,5.5)) @@ -7867,7 +7867,7 @@ EEIIIYTP+v/YLseLtZ7EnQAAAABJRU5ErkJggg== In [19]: -``` +```py xi = [x0] result = minimize(rosen, x0, method="powell", callback=xi.append) xi = np.asarray(xi) @@ -7876,7 +7876,7 @@ print "Solved Powell's method with {} function evaluations.".format(result.nfev) ``` -``` +```py (31L, 2L) Solved Powell's method with 855 function evaluations. @@ -7884,7 +7884,7 @@ Solved Powell's method with 855 function evaluations. In [20]: -``` +```py x, y = meshgrid(np.linspace(-2.3,1.75,25), np.linspace(-0.5,4.5,25)) z = rosen([x,y]) fig = figure(figsize=(12,5.5)) diff --git a/docs/da/058.md b/docs/da/058.md index 1638a05f5..ac78c018b 100644 --- a/docs/da/058.md +++ b/docs/da/058.md @@ -12,7 +12,7 @@ $$\frac{d}{dx} F(x) = f(x) \Rightarrow F(x) = \int f(x) dx$$ In [1]: -``` +```py from sympy import init_printing init_printing() @@ -20,7 +20,7 @@ init_printing() In [2]: -``` +```py from sympy import symbols, integrate import sympy @@ -30,7 +30,7 @@ import sympy In [3]: -``` +```py x, y = symbols('x y') sympy.sqrt(x ** 2 + y ** 2) @@ -42,7 +42,7 @@ Out[3]:$$\sqrt{x^{2} + y^{2}}$$ In [4]: -``` +```py z = sympy.sqrt(x ** 2 + y ** 2) z.subs(x, 3) @@ -54,7 +54,7 @@ Out[4]:$$\sqrt{y^{2} + 9}$$ In [5]: -``` +```py z.subs(x, 3).subs(y, 4) ``` @@ -65,7 +65,7 @@ Out[5]:$$5$$ In [6]: -``` +```py from sympy.abc import theta y = sympy.sin(theta) ** 2 y @@ -78,7 +78,7 @@ Out[6]:$$\sin^{2}{\left (\theta \right )}$$ In [7]: -``` +```py Y = integrate(y) Y @@ -90,7 +90,7 @@ Out[7]:$$\frac{\theta}{2} - \frac{1}{2} \sin{\left (\theta \right )} \cos{\left In [8]: -``` +```py import numpy as np np.set_printoptions(precision=3) @@ -104,7 +104,7 @@ Out[8]:$$1.5707963267949$$ In [9]: -``` +```py integrate(y, (theta, 0, sympy.pi)) ``` @@ -115,14 +115,14 @@ Out[9]:$$\frac{\pi}{2}$$ In [10]: -``` +```py integrate(y, (theta, 0, sympy.pi)).evalf() ``` Out[10]:$$1.5707963267949$$In [11]: -``` +```py integrate(y, (theta, 0, np.pi)) ``` @@ -135,7 +135,7 @@ Out[11]:$$1.5707963267949$$ In [12]: -``` +```py Y_indef = sympy.Integral(y) Y_indef @@ -143,12 +143,12 @@ Y_indef Out[12]:$$\int \sin^{2}{\left (\theta \right )}\, d\theta$$In [13]: -``` +```py print type(Y_indef) ``` -``` +```py ``` @@ -157,7 +157,7 @@ print type(Y_indef) In [14]: -``` +```py Y_def = sympy.Integral(y, (theta, 0, sympy.pi)) Y_def @@ -169,7 +169,7 @@ Out[14]:$$\int_{0}^{\pi} \sin^{2}{\left (\theta \right )}\, d\theta$$ In [15]: -``` +```py Y_raw = lambda x: integrate(y, (theta, 0, x)) Y = np.vectorize(Y_raw) @@ -177,7 +177,7 @@ Y = np.vectorize(Y_raw) In [16]: -``` +```py %matplotlib inline import matplotlib.pyplot as plt @@ -356,14 +356,14 @@ $$F(x) = \lim_{n \rightarrow \infty} \sum_{i=0}^{n-1} f(x_i)(x_{i+1}-x_i) \Right In [17]: -``` +```py from scipy.special import jv ``` In [18]: -``` +```py def f(x): return jv(2.5, x) @@ -371,7 +371,7 @@ def f(x): In [19]: -``` +```py x = np.linspace(0, 10) p = plt.plot(x, f(x), 'k-') @@ -594,7 +594,7 @@ quad 返回一个 (积分值,误差) 组成的元组: In [20]: -``` +```py from scipy.integrate import quad interval = [0, 6.5] value, max_err = quad(f, *interval) @@ -605,12 +605,12 @@ value, max_err = quad(f, *interval) In [21]: -``` +```py print value ``` -``` +```py 1.28474297234 ``` @@ -619,12 +619,12 @@ print value In [22]: -``` +```py print max_err ``` -``` +```py 2.34181853668e-09 ``` @@ -633,7 +633,7 @@ print max_err In [23]: -``` +```py print "integral = {:.9f}".format(value) print "upper bound on error: {:.2e}".format(max_err) x = np.linspace(0, 10, 100) @@ -644,7 +644,7 @@ p = plt.fill_between(x, f(x), where=f(x)<0, color="red", interpolate=True) ``` -``` +```py integral = 1.284742972 upper bound on error: 2.34e-09 @@ -854,7 +854,7 @@ R6zoG2NMHLGib4wxceT/AZhppPNX9o1QAAAAAElFTkSuQmCC In [24]: -``` +```py from numpy import inf interval = [0., inf] @@ -865,7 +865,7 @@ def g(x): In [25]: -``` +```py value, max_err = quad(g, *interval) x = np.linspace(0, 10, 50) fig = plt.figure(figsize=(10,3)) @@ -877,7 +877,7 @@ print "upper bound on error: {:.1e}".format(max_err) ``` -``` +```py upper bound on error: 7.2e-11 ``` @@ -1083,7 +1083,7 @@ TkSuQmCC $$ I_n = \int \limits_0^{\infty} \int \limits_1^{\infty} \frac{e^{-xt}}{t^n}dt dx = \frac{1}{n}$$In [26]: -``` +```py def h(x, t, n): """core function, takes x, t, n""" return np.exp(-x * t) / (t ** n) @@ -1094,7 +1094,7 @@ def h(x, t, n): In [27]: -``` +```py from numpy import vectorize @vectorize def int_h_dx(t, n): @@ -1105,7 +1105,7 @@ def int_h_dx(t, n): In [28]: -``` +```py @vectorize def I_n(n): return quad(int_h_dx, 1, np.inf, args=(n)) @@ -1114,14 +1114,14 @@ def I_n(n): In [29]: -``` +```py I_n([0.5, 1.0, 2.0, 5]) ``` Out[29]: -``` +```py (array([ 1.97, 1\. , 0.5 , 0.2 ]), array([ 9.804e-13, 1.110e-14, 5.551e-15, 2.220e-15])) ``` @@ -1130,7 +1130,7 @@ Out[29]: In [30]: -``` +```py from scipy.integrate import dblquad @vectorize def I(n): @@ -1145,14 +1145,14 @@ def I(n): In [31]: -``` +```py I_n([0.5, 1.0, 2.0, 5]) ``` Out[31]: -``` +```py (array([ 1.97, 1\. , 0.5 , 0.2 ]), array([ 9.804e-13, 1.110e-14, 5.551e-15, 2.220e-15])) ``` @@ -1163,7 +1163,7 @@ Out[31]: In [32]: -``` +```py from scipy.integrate import trapz, simps ``` @@ -1172,7 +1172,7 @@ from scipy.integrate import trapz, simps In [33]: -``` +```py x_s = np.linspace(0, np.pi, 5) y_s = np.sin(x_s) x = np.linspace(0, np.pi, 100) @@ -1182,7 +1182,7 @@ y = np.sin(x) In [34]: -``` +```py p = plt.plot(x, y, 'k:') p = plt.plot(x_s, y_s, 'k+-') p = plt.fill_between(x_s, y_s, color="gray") @@ -1416,7 +1416,7 @@ QmCC In [35]: -``` +```py result_s = trapz(y_s, x_s) result_s_s = simps(y_s, x_s) result = trapz(y, x) @@ -1426,7 +1426,7 @@ print "Trapezoidal Integration over 100 points : {:.3f}".format(result) ``` -``` +```py Trapezoidal Integration over 5 points : 1.896 Simpson Integration over 5 points : 2.005 Trapezoidal Integration over 100 points : 2.000 @@ -1439,25 +1439,25 @@ Trapezoidal Integration over 100 points : 2.000 In [36]: -``` +```py type(np.add) ``` Out[36]: -``` +```py numpy.ufunc ``` In [37]: -``` +```py np.info(np.add.accumulate) ``` -``` +```py accumulate(array, axis=0, dtype=None, out=None) Accumulate the result of applying the operator to all elements. @@ -1534,14 +1534,14 @@ array([[ 1., 1.], In [38]: -``` +```py result_np = np.add.accumulate(y) * (x[1] - x[0]) - (x[1] - x[0]) / 2 ``` In [39]: -``` +```py p = plt.plot(x, - np.cos(x) + np.cos(0), 'rx') p = plt.plot(x, result_np) @@ -1719,7 +1719,7 @@ RoFfRCTGKPCLiMSY/weoVZxsAST89wAAAABJRU5ErkJggg== In [40]: -``` +```py import sympy from sympy.abc import x, theta sympy_x = x @@ -1728,7 +1728,7 @@ sympy_x = x In [41]: -``` +```py x = np.linspace(0, 20 * np.pi, 1e+4) y = np.sin(x) sympy_y = vectorize(lambda x: sympy.integrate(sympy.sin(theta), (theta, 0, x))) @@ -1739,14 +1739,14 @@ sympy_y = vectorize(lambda x: sympy.integrate(sympy.sin(theta), (theta, 0, x))) In [42]: -``` +```py %timeit np.add.accumulate(y) * (x[1] - x[0]) y0 = np.add.accumulate(y) * (x[1] - x[0]) print y0[-1] ``` -``` +```py The slowest run took 4.32 times longer than the fastest. This could mean that an intermediate result is being cached 10000 loops, best of 3: 56.2 µs per loop -2.34138044756e-17 @@ -1757,7 +1757,7 @@ The slowest run took 4.32 times longer than the fastest. This could mean that an In [43]: -``` +```py %timeit quad(np.sin, 0, 20 * np.pi) y2 = quad(np.sin, 0, 20 * np.pi, full_output=True) print "result = ", y2[0] @@ -1765,7 +1765,7 @@ print "number of evaluations", y2[-1]['neval'] ``` -``` +```py 10000 loops, best of 3: 40.5 µs per loop result = 3.43781337153e-15 number of evaluations 21 @@ -1776,14 +1776,14 @@ number of evaluations 21 In [44]: -``` +```py %timeit trapz(y, x) y1 = trapz(y, x) print y1 ``` -``` +```py 10000 loops, best of 3: 105 µs per loop -4.4408920985e-16 @@ -1793,14 +1793,14 @@ print y1 In [45]: -``` +```py %timeit simps(y, x) y3 = simps(y, x) print y3 ``` -``` +```py 1000 loops, best of 3: 801 µs per loop 3.28428554968e-16 @@ -1810,14 +1810,14 @@ print y3 In [46]: -``` +```py %timeit sympy_y(20 * np.pi) y4 = sympy_y(20 * np.pi) print y4 ``` -``` +```py 100 loops, best of 3: 6.86 ms per loop 0 diff --git a/docs/da/059.md b/docs/da/059.md index 03d43e379..881f75063 100644 --- a/docs/da/059.md +++ b/docs/da/059.md @@ -2,12 +2,12 @@ In [1]: -``` +```py %pylab inline ``` -``` +```py Populating the interactive namespace from numpy and matplotlib ``` @@ -18,7 +18,7 @@ Populating the interactive namespace from numpy and matplotlib $$\frac{dy}{dt} = sin(t)$$In [2]: -``` +```py def dy_dt(y, t): return np.sin(t) @@ -28,7 +28,7 @@ def dy_dt(y, t): In [3]: -``` +```py from scipy.integrate import odeint t = np.linspace(0, 2*pi, 100) @@ -39,7 +39,7 @@ result = odeint(dy_dt, 0, t) In [4]: -``` +```py fig = figure(figsize=(12,4)) p = plot(t, result, "rx", label=r"$\int_{0}^{x}sin(t) dt $") p = plot(t, -cos(t) + cos(0), label=r"$cos(0) - cos(t)$") @@ -494,7 +494,7 @@ $$ \frac{d^2x}{dt^2} = g - \frac{D}{m}\frac{dx}{dt} $$ $$y = \left[x, \frac{dx}{dt}\right] $$$$\begin{aligned} \frac{dy_0}{dt} &= y_1 \\\ \frac{dy_1}{dt} &= -g - \frac{D}{m} y_1 \\\ \end{aligned} $$In [5]: -``` +```py def dy_dt(y, t): """Governing equations for projectile motion with drag. y[0] = position @@ -514,7 +514,7 @@ def dy_dt(y, t): In [6]: -``` +```py position_0 = 0. velocity_0 = 100 t = linspace(0, 12, 100) @@ -524,7 +524,7 @@ y = odeint(dy_dt, [position_0, velocity_0], t) In [7]: -``` +```py p = plot(t, y[:,0]) yl = ylabel("Height (m)") xl = xlabel("Time (s)") @@ -705,7 +705,7 @@ Jc7ptLGpsCKZphaESJYlprDexaa3fDwUeFTJQWJSC0JERJJSC0JERJJSghARkaSUIEREJCklCBER SUoJQkREklKCEBGRpP4fPzntqp99LaMAAAAASUVORK5CYII= )In [8]: -``` +```py y, infodict = odeint(dy_dt, [position_0, velocity_0], t, full_output=True, printmessg=True, ) print sorted(infodict.keys()) print "cumulative number of function evaluations at each calculated point:", infodict['nfe'] @@ -713,7 +713,7 @@ print "cumulative number of time steps", infodict['nst'] ``` -``` +```py Integration successful. ['hu', 'imxer', 'leniw', 'lenrw', 'message', 'mused', 'nfe', 'nje', 'nqu', 'nst', 'tcur', 'tolsf', 'tsw'] cumulative number of function evaluations at each calculated point: [ 45 49 51 53 55 59 61 61 63 65 67 67 69 71 73 73 75 77 diff --git a/docs/da/060.md b/docs/da/060.md index 630b007c0..91b71d3f9 100644 --- a/docs/da/060.md +++ b/docs/da/060.md @@ -23,7 +23,7 @@ In [1]: -``` +```py from scipy.sparse import * import numpy as np @@ -33,14 +33,14 @@ import numpy as np In [2]: -``` +```py coo_matrix((2,3)) ``` Out[2]: -``` +```py <2x3 sparse matrix of type '' with 0 stored elements in COOrdinate format> ``` @@ -49,13 +49,13 @@ Out[2]: In [3]: -``` +```py A = coo_matrix([[1,2,0],[0,0,3],[4,0,5]]) print A ``` -``` +```py (0, 0) 1 (0, 1) 2 (1, 2) 3 @@ -68,20 +68,20 @@ print A In [4]: -``` +```py type(A) ``` Out[4]: -``` +```py scipy.sparse.coo.coo_matrix ``` In [5]: -``` +```py B = A.tocsr() type(B) @@ -89,7 +89,7 @@ type(B) Out[5]: -``` +```py scipy.sparse.csr.csr_matrix ``` @@ -97,7 +97,7 @@ scipy.sparse.csr.csr_matrix In [6]: -``` +```py C = A.todense() C @@ -105,7 +105,7 @@ C Out[6]: -``` +```py matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) @@ -115,7 +115,7 @@ matrix([[1, 2, 0], In [7]: -``` +```py v = np.array([1,0,-1]) A.dot(v) @@ -123,7 +123,7 @@ A.dot(v) Out[7]: -``` +```py array([ 1, -3, -1]) ``` @@ -131,7 +131,7 @@ array([ 1, -3, -1]) In [8]: -``` +```py I = np.array([0,3,1,0]) J = np.array([0,3,1,2]) V = np.array([4,5,7,9]) @@ -141,12 +141,12 @@ A = coo_matrix((V,(I,J)),shape=(4,4)) In [9]: -``` +```py print A ``` -``` +```py (0, 0) 4 (3, 3) 5 (1, 1) 7 @@ -158,7 +158,7 @@ COO 格式的稀疏矩阵在构建的时候只是简单的将坐标和值加到 In [10]: -``` +```py I = np.array([0,0,1,3,1,0,0]) J = np.array([0,2,1,3,1,0,0]) V = np.array([1,1,1,1,1,1,1]) @@ -167,7 +167,7 @@ print B ``` -``` +```py (0, 0) 1 (0, 2) 1 (1, 1) 1 @@ -182,13 +182,13 @@ print B In [11]: -``` +```py C = B.tocsr() print C ``` -``` +```py (0, 0) 3 (0, 2) 1 (1, 1) 2 @@ -200,7 +200,7 @@ print C In [12]: -``` +```py from scipy.sparse import lil_matrix from scipy.sparse.linalg import spsolve from numpy.linalg import solve, norm @@ -212,7 +212,7 @@ from numpy.random import rand In [13]: -``` +```py A = lil_matrix((1000, 1000)) A[0, :100] = rand(100) A[1, 100:200] = A[0, :100] @@ -224,7 +224,7 @@ A.setdiag(rand(1000)) In [14]: -``` +```py A = A.tocsr() b = rand(1000) x = spsolve(A, b) @@ -235,7 +235,7 @@ x = spsolve(A, b) In [15]: -``` +```py x_ = solve(A.toarray(), b) ``` @@ -244,7 +244,7 @@ x_ = solve(A.toarray(), b) In [16]: -``` +```py err = norm(x-x_) err @@ -252,7 +252,7 @@ err Out[16]: -``` +```py 6.4310987107687431e-13 ``` @@ -262,7 +262,7 @@ Out[16]: In [17]: -``` +```py from scipy import sparse row, col, val = sparse.find(C) @@ -270,7 +270,7 @@ print row, col, val ``` -``` +```py [0 0 1 3] [0 2 1 3] [3 1 2 1] ``` @@ -281,14 +281,14 @@ print row, col, val In [18]: -``` +```py sparse.issparse(B) ``` Out[18]: -``` +```py True ``` @@ -296,14 +296,14 @@ True In [19]: -``` +```py sparse.isspmatrix(B.todense()) ``` Out[19]: -``` +```py False ``` @@ -311,26 +311,26 @@ False In [20]: -``` +```py sparse.isspmatrix_coo(B) ``` Out[20]: -``` +```py True ``` In [21]: -``` +```py sparse.isspmatrix_csr(B) ``` Out[21]: -``` +```py False ``` \ No newline at end of file diff --git a/docs/da/061.md b/docs/da/061.md index 831aad98a..0166c398b 100644 --- a/docs/da/061.md +++ b/docs/da/061.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np import numpy.linalg import scipy as sp @@ -28,13 +28,13 @@ from scipy import linalg In [2]: -``` +```py print "number of items in numpy.linalg:", len(dir(numpy.linalg)) print "number of items in scipy.linalg:", len(dir(scipy.linalg)) ``` -``` +```py number of items in numpy.linalg: 36 number of items in scipy.linalg: 115 @@ -56,7 +56,7 @@ number of items in scipy.linalg: 115 In [3]: -``` +```py A = np.mat("[1, 2; 3, 4]") print repr(A) @@ -65,7 +65,7 @@ print repr(A) ``` -``` +```py matrix([[1, 2], [3, 4]]) matrix([[1, 2], @@ -77,13 +77,13 @@ matrix([[1, 2], In [4]: -``` +```py print repr(A.I) print repr(A.T) ``` -``` +```py matrix([[-2\. , 1\. ], [ 1.5, -0.5]]) matrix([[1, 3], @@ -95,13 +95,13 @@ matrix([[1, 3], In [5]: -``` +```py b = np.mat('[5; 6]') print repr(A * b) ``` -``` +```py matrix([[17], [39]]) @@ -115,13 +115,13 @@ matrix([[17], In [6]: -``` +```py A = np.array([[1,2], [3,4]]) print repr(A) ``` -``` +```py array([[1, 2], [3, 4]]) @@ -131,13 +131,13 @@ array([[1, 2], In [7]: -``` +```py print repr(linalg.inv(A)) print repr(A.T) ``` -``` +```py array([[-2\. , 1\. ], [ 1.5, -0.5]]) array([[1, 3], @@ -149,14 +149,14 @@ array([[1, 3], In [8]: -``` +```py b = np.array([5, 6]) print repr(A.dot(b)) ``` -``` +```py array([17, 39]) ``` @@ -165,12 +165,12 @@ array([17, 39]) In [9]: -``` +```py print repr(A * b) ``` -``` +```py array([[ 5, 12], [15, 24]]) @@ -188,7 +188,7 @@ array([[ 5, 12], In [10]: -``` +```py A = np.array([[1,2],[3,4]]) print linalg.inv(A) @@ -197,7 +197,7 @@ print A.dot(scipy.linalg.inv(A)) ``` -``` +```py [[-2\. 1\. ] [ 1.5 -0.5]] [[ 1.00000000e+00 0.00000000e+00] @@ -213,7 +213,7 @@ print A.dot(scipy.linalg.inv(A)) In [11]: -``` +```py import time A = np.array([[1, 3, 5], @@ -241,7 +241,7 @@ print "solve: {} s".format(time.time() - tic) ``` -``` +```py [-9.28 5.16 0.76] [ 0.00000000e+00 -1.77635684e-15 -8.88178420e-16] inv and dot: 0.0353579521179 s @@ -263,7 +263,7 @@ solve: 0.0284671783447 s In [12]: -``` +```py A = np.array([[1, 3, 5], [2, 5, 1], [2, 3, 8]]) @@ -272,7 +272,7 @@ print linalg.det(A) ``` -``` +```py -25.0 ``` @@ -287,7 +287,7 @@ print linalg.det(A) In [13]: -``` +```py A = np.array([[1, 2], [3, 4]]) @@ -303,7 +303,7 @@ print linalg.norm(A,np.inf) # L inf norm 最大行和 ``` -``` +```py 5.47722557505 5.47722557505 6 @@ -350,7 +350,7 @@ $$ y_{i}=\sum_{j}c_{j}f_{j}\left(\mathbf{x}_{i}\right)+\epsilon_{i} $$ In [14]: -``` +```py c1, c2 = 5.0, 2.0 i = np.r_[1:11] xi = 0.1*i @@ -363,13 +363,13 @@ zi = yi + 0.05 * np.max(yi) * np.random.randn(len(yi)) In [15]: -``` +```py A = np.c_[np.exp(-xi)[:, np.newaxis], xi[:, np.newaxis]] print A ``` -``` +```py [[ 0.90483742 0.1 ] [ 0.81873075 0.2 ] [ 0.74081822 0.3 ] @@ -387,14 +387,14 @@ print A In [16]: -``` +```py c, resid, rank, sigma = linalg.lstsq(A, zi) print c ``` -``` +```py [ 4.87016856 2.19081311] ``` @@ -405,7 +405,7 @@ print c In [17]: -``` +```py xi2 = np.r_[0.1:1.0:100j] yi2 = c[0]*np.exp(-xi2) + c[1]*xi2 @@ -608,7 +608,7 @@ gIuIRNT/AXU6OlSJKzNiAAAAAElFTkSuQmCC In [18]: -``` +```py A = np.array([[1, 5, 2], [2, 4, 1], [3, 6, 2]]) @@ -630,7 +630,7 @@ print linalg.norm(A.dot(v1)-l1*v1) ``` -``` +```py [ 7.95791620+0.j -1.25766471+0.j 0.29974850+0.j] [ 1\. 1\. 1.] 3.23301824835e-15 @@ -660,7 +660,7 @@ $M \times N$ 矩阵 $\mathbf A$ 的奇异值分解为: $$ \mathbf{A=U}\boldsym In [19]: -``` +```py A = np.array([[1,2,3],[4,5,6]]) U, s, Vh = linalg.svd(A) @@ -671,7 +671,7 @@ $\boldsymbol{\Sigma}$ 矩阵: In [20]: -``` +```py M, N = A.shape Sig = linalg.diagsvd(s,M,N) @@ -679,7 +679,7 @@ print Sig ``` -``` +```py [[ 9.508032 0\. 0\. ] [ 0\. 0.77286964 0\. ]] @@ -689,13 +689,13 @@ print Sig In [21]: -``` +```py print A print U.dot(Sig.dot(Vh)) ``` -``` +```py [[1 2 3] [4 5 6]] [[ 1\. 2\. 3.] @@ -715,7 +715,7 @@ $\mathbf P$ 是 $M \times M$ 的单位矩阵的一个排列,$\mathbf L$ 是下 In [22]: -``` +```py A = np.array([[1,2,3],[4,5,6]]) P, L, U = linalg.lu(A) @@ -728,7 +728,7 @@ print P.dot(L).dot(U) ``` -``` +```py [[ 0\. 1.] [ 1\. 0.]] [[ 1\. 0\. ] @@ -768,7 +768,7 @@ $\mathbf R$ 为上三角形矩阵,$\mathbf Q$ 是正交矩阵。 In [23]: -``` +```py A = np.mat('[1 3 2; 1 4 5; 2 3 6]') print A @@ -781,7 +781,7 @@ print Z.dot(T).dot(Z.T) ``` -``` +```py [[1 3 2] [1 4 5] [2 3 6]] @@ -814,14 +814,14 @@ print Z.dot(T).dot(Z.T) In [24]: -``` +```py A = np.array([[1, 2], [3, 4]]) print linalg.expm3(A) ``` -``` +```py [[ 51.96890355 74.73648784] [ 112.10473176 164.07363531]] @@ -835,12 +835,12 @@ print linalg.expm3(A) In [25]: -``` +```py print linalg.expm2(A) ``` -``` +```py [[ 51.9689562 74.73656457] [ 112.10484685 164.07380305]] @@ -852,12 +852,12 @@ print linalg.expm2(A) In [26]: -``` +```py print linalg.expm(A) ``` -``` +```py [[ 51.9689562 74.73656457] [ 112.10484685 164.07380305]] @@ -869,13 +869,13 @@ print linalg.expm(A) In [27]: -``` +```py print A print linalg.logm(linalg.expm(A)) ``` -``` +```py [[1 2] [3 4]] [[ 1\. 2.] diff --git a/docs/da/062.md b/docs/da/062.md index db4d94d10..c2e440a24 100644 --- a/docs/da/062.md +++ b/docs/da/062.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import scipy.sparse.linalg ``` diff --git a/docs/da/064.md b/docs/da/064.md index 0dcb60c4b..8a55beb2a 100644 --- a/docs/da/064.md +++ b/docs/da/064.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import sys ``` @@ -13,14 +13,14 @@ import sys In [2]: -``` +```py %%writefile print_args.py import sys print sys.argv ``` -``` +```py Writing print_args.py ``` @@ -29,12 +29,12 @@ Writing print_args.py In [3]: -``` +```py %run print_args.py 1 foo ``` -``` +```py ['print_args.py', '1', 'foo'] ``` @@ -45,7 +45,7 @@ In [3]: In [4]: -``` +```py import os os.remove('print_args.py') @@ -57,7 +57,7 @@ os.remove('print_args.py') In [5]: -``` +```py try: x = 1/0 except Exception: @@ -65,7 +65,7 @@ except Exception: ``` -``` +```py (, ZeroDivisionError('integer division or modulo by zero',), ) ``` @@ -88,14 +88,14 @@ except Exception: In [6]: -``` +```py sys.path ``` Out[6]: -``` +```py ['', 'C:\\Anaconda\\python27.zip', 'C:\\Anaconda\\DLLs', @@ -125,14 +125,14 @@ Out[6]: In [7]: -``` +```py sys.platform ``` Out[7]: -``` +```py 'win32' ``` @@ -140,14 +140,14 @@ Out[7]: In [8]: -``` +```py sys.getwindowsversion() ``` Out[8]: -``` +```py sys.getwindowsversion(major=6, minor=2, build=9200, platform=2, service_pack='') ``` @@ -157,26 +157,26 @@ sys.getwindowsversion(major=6, minor=2, build=9200, platform=2, service_pack='') In [9]: -``` +```py sys.version ``` Out[9]: -``` +```py '2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]' ``` In [10]: -``` +```py sys.version_info ``` Out[10]: -``` +```py sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0) ``` \ No newline at end of file diff --git a/docs/da/065.md b/docs/da/065.md index bf69d7cd1..47f915aff 100644 --- a/docs/da/065.md +++ b/docs/da/065.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import os ``` @@ -26,14 +26,14 @@ import os In [2]: -``` +```py os.getcwd() ``` Out[2]: -``` +```py '/home/lijin/notes-python/05\. advanced python' ``` @@ -41,14 +41,14 @@ Out[2]: In [3]: -``` +```py os.curdir ``` Out[3]: -``` +```py '.' ``` @@ -56,14 +56,14 @@ Out[3]: In [4]: -``` +```py os.listdir(os.curdir) ``` Out[4]: -``` +```py ['05.01 overview of the sys module.ipynb', '05.05 datetime.ipynb', '05.13 decorator usage.ipynb', @@ -88,7 +88,7 @@ Out[4]: In [5]: -``` +```py f = open("test.file", "w") f.close() @@ -96,7 +96,7 @@ print "test.file" in os.listdir(os.curdir) ``` -``` +```py True ``` @@ -105,7 +105,7 @@ True In [6]: -``` +```py os.rename("test.file", "test.new.file") print "test.file" in os.listdir(os.curdir) @@ -113,7 +113,7 @@ print "test.new.file" in os.listdir(os.curdir) ``` -``` +```py False True @@ -123,7 +123,7 @@ True In [7]: -``` +```py os.remove("test.new.file") ``` @@ -134,7 +134,7 @@ os.remove("test.new.file") In [8]: -``` +```py # windows 为 \r\n os.linesep @@ -142,7 +142,7 @@ os.linesep Out[8]: -``` +```py '\n' ``` @@ -150,14 +150,14 @@ Out[8]: In [9]: -``` +```py os.sep ``` Out[9]: -``` +```py '/' ``` @@ -165,14 +165,14 @@ Out[9]: In [10]: -``` +```py os.pathsep ``` Out[10]: -``` +```py ':' ``` @@ -182,14 +182,14 @@ Out[10]: In [11]: -``` +```py os.environ["USER"] ``` Out[11]: -``` +```py 'lijin' ``` @@ -201,7 +201,7 @@ Out[11]: In [12]: -``` +```py import os.path ``` diff --git a/docs/da/066.md b/docs/da/066.md index f0129f611..c405e4a9e 100644 --- a/docs/da/066.md +++ b/docs/da/066.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import csv ``` @@ -15,7 +15,7 @@ import csv In [2]: -``` +```py %%file data.csv "alpha 1", 100, -1.443 "beat 3", 12, -0.0934 @@ -24,7 +24,7 @@ In [2]: ``` -``` +```py Writing data.csv ``` @@ -33,7 +33,7 @@ Writing data.csv In [3]: -``` +```py fp = open("data.csv") r = csv.reader(fp) @@ -43,7 +43,7 @@ r = csv.reader(fp) In [4]: -``` +```py for row in r: print row @@ -51,7 +51,7 @@ fp.close() ``` -``` +```py ['alpha 1', ' 100', ' -1.443'] ['beat 3', ' 12', ' -0.0934'] ['gamma 3a', ' 192', ' -0.6621'] @@ -63,7 +63,7 @@ fp.close() In [5]: -``` +```py data = [] with open('data.csv') as fp: @@ -77,7 +77,7 @@ data Out[5]: -``` +```py [['alpha 1', 100, -1.443], ['beat 3', 12, -0.0934], ['gamma 3a', 192, -0.6621], @@ -86,7 +86,7 @@ Out[5]: In [6]: -``` +```py import os os.remove('data.csv') @@ -98,7 +98,7 @@ os.remove('data.csv') In [7]: -``` +```py data = [('one', 1, 1.5), ('two', 2, 8.0)] with open('out.csv', 'wb') as fp: w = csv.writer(fp) @@ -110,12 +110,12 @@ with open('out.csv', 'wb') as fp: In [8]: -``` +```py !cat 'out.csv' ``` -``` +```py one,1,1.5 two,2,8.0 @@ -127,7 +127,7 @@ two,2,8.0 In [9]: -``` +```py data = [('one, \"real\" string', 1, 1.5), ('two', 2, 8.0)] with open('out.csv', 'wb') as fp: w = csv.writer(fp) @@ -137,12 +137,12 @@ with open('out.csv', 'wb') as fp: In [10]: -``` +```py !cat 'out.csv' ``` -``` +```py "one, ""real"" string",1,1.5 two,2,8.0 @@ -152,7 +152,7 @@ two,2,8.0 In [11]: -``` +```py data = [('one, \"real\" string', 1, 1.5), ('two', 2, 8.0)] with open('out.psv', 'wb') as fp: w = csv.writer(fp, delimiter="|") @@ -162,12 +162,12 @@ with open('out.psv', 'wb') as fp: In [12]: -``` +```py !cat 'out.psv' ``` -``` +```py "one, ""real"" string"|1|1.5 two|2|8.0 @@ -175,7 +175,7 @@ two|2|8.0 In [13]: -``` +```py import os os.remove('out.psv') os.remove('out.csv') @@ -188,7 +188,7 @@ os.remove('out.csv') In [14]: -``` +```py %%file trades.csv Order,Date,Stock,Quantity,Price A0001,2013-12-01,AAPL,1000,203.4 @@ -197,7 +197,7 @@ A0003,2013-12-02,GOOG,1500,167.5 ``` -``` +```py Writing trades.csv ``` @@ -206,14 +206,14 @@ Writing trades.csv In [15]: -``` +```py import pandas df = pandas.read_csv('trades.csv', index_col=0) print df ``` -``` +```py Date Stock Quantity Price Order A0001 2013-12-01 AAPL 1000 203.4 @@ -226,14 +226,14 @@ A0003 2013-12-02 GOOG 1500 167.5 In [16]: -``` +```py df['Quantity'] * df['Price'] ``` Out[16]: -``` +```py Order A0001 203400 A0002 251250 @@ -243,7 +243,7 @@ dtype: float64 In [17]: -``` +```py import os os.remove('trades.csv') diff --git a/docs/da/067.md b/docs/da/067.md index 7fedf4b92..3b1ff0eb1 100644 --- a/docs/da/067.md +++ b/docs/da/067.md @@ -8,7 +8,7 @@ In [1]: -``` +```py import re ``` @@ -17,7 +17,7 @@ import re 在 `re` 模块中, `re.match` 和 `re.search` 是常用的两个方法: -``` +```py re.match(pattern, string[, flags]) re.search(pattern, string[, flags]) ``` @@ -74,7 +74,7 @@ re.search(pattern, string[, flags]) In [2]: -``` +```py string = 'hello world' pattern = 'hello (\w+)' @@ -83,7 +83,7 @@ print match ``` -``` +```py <_sre.SRE_Match object at 0x0000000003A5DA80> ``` @@ -92,26 +92,26 @@ print match In [3]: -``` +```py if match is not None: print match.group(0) ``` -``` +```py hello world ``` In [4]: -``` +```py if match is not None: print match.group(1) ``` -``` +```py world ``` @@ -120,7 +120,7 @@ world In [5]: -``` +```py string = 'hello there' pattern = 'hello (\w+)' @@ -131,7 +131,7 @@ if match is not None: ``` -``` +```py hello there there @@ -143,7 +143,7 @@ there In [6]: -``` +```py pattern1 = re.compile('hello (\w+)') match = pattern1.match(string) @@ -152,7 +152,7 @@ if match is not None: ``` -``` +```py there ``` @@ -163,13 +163,13 @@ there In [7]: -``` +```py pattern = '\\' print pattern ``` -``` +```py \ ``` @@ -178,14 +178,14 @@ print pattern In [8]: -``` +```py pattern = '\\\\' path = "C:\\foo\\bar\\baz.txt" print re.split(pattern, path) ``` -``` +```py ['C:', 'foo', 'bar', 'baz.txt'] ``` @@ -194,14 +194,14 @@ print re.split(pattern, path) In [9]: -``` +```py pattern = r'\\' path = r"C:\foo\bar\baz.txt" print re.split(pattern, path) ``` -``` +```py ['C:', 'foo', 'bar', 'baz.txt'] ``` @@ -212,7 +212,7 @@ print re.split(pattern, path) In [10]: -``` +```py %%file test.dat 1312 foo 1534 bar @@ -220,12 +220,12 @@ In [10]: ``` -``` +```py Writing test.dat ``` -``` +```py fromregex(file, pattern, dtype) ``` @@ -233,7 +233,7 @@ fromregex(file, pattern, dtype) In [11]: -``` +```py pattern = "(\d+)\s+(...)" dt = [('num', 'int64'), ('key', 'S3')] @@ -243,7 +243,7 @@ print output ``` -``` +```py [(1312L, 'foo') (1534L, 'bar') (444L, 'qux')] ``` @@ -252,19 +252,19 @@ print output In [12]: -``` +```py print output['num'] ``` -``` +```py [1312 1534 444] ``` In [13]: -``` +```py import os os.remove('test.dat') diff --git a/docs/da/068.md b/docs/da/068.md index 27a3b8f5e..6f09b2f45 100644 --- a/docs/da/068.md +++ b/docs/da/068.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import datetime as dt ``` @@ -15,7 +15,7 @@ import datetime as dt In [2]: -``` +```py d1 = dt.date(2007, 9, 25) d2 = dt.date(2008, 9, 25) @@ -25,14 +25,14 @@ d2 = dt.date(2008, 9, 25) In [3]: -``` +```py print d1 print d1.strftime('%A, %m/%d/%y') print d1.strftime('%a, %m-%d-%Y') ``` -``` +```py 2007-09-25 Tuesday, 09/25/07 Tue, 09-25-2007 @@ -43,12 +43,12 @@ Tue, 09-25-2007 In [4]: -``` +```py print d2 - d1 ``` -``` +```py 366 days, 0:00:00 ``` @@ -57,14 +57,14 @@ print d2 - d1 In [5]: -``` +```py d = d2 - d1 print d.days print d.seconds ``` -``` +```py 366 0 @@ -74,12 +74,12 @@ print d.seconds In [6]: -``` +```py print dt.date.today() ``` -``` +```py 2015-09-10 ``` @@ -90,7 +90,7 @@ print dt.date.today() In [7]: -``` +```py t1 = dt.time(15, 38) t2 = dt.time(18) @@ -100,14 +100,14 @@ t2 = dt.time(18) In [8]: -``` +```py print t1 print t1.strftime('%I:%M, %p') print t1.strftime('%H:%M:%S, %p') ``` -``` +```py 15:38:00 03:38, PM 15:38:00, PM @@ -124,13 +124,13 @@ print t1.strftime('%H:%M:%S, %p') In [9]: -``` +```py d1 = dt.datetime.now() print d1 ``` -``` +```py 2015-09-10 20:58:50.148000 ``` @@ -139,13 +139,13 @@ print d1 In [10]: -``` +```py d2 = d1 + dt.timedelta(30) print d2 ``` -``` +```py 2015-10-10 20:58:50.148000 ``` @@ -154,12 +154,12 @@ print d2 In [11]: -``` +```py print dt.datetime.strptime('2/10/01', '%m/%d/%y') ``` -``` +```py 2001-02-10 00:00:00 ``` diff --git a/docs/da/069.md b/docs/da/069.md index 59ff7fa5f..c4d1e26a8 100644 --- a/docs/da/069.md +++ b/docs/da/069.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import sqlite3 as db ``` @@ -13,14 +13,14 @@ import sqlite3 as db In [2]: -``` +```py connection = db.connect("my_database.sqlite") ``` 不同的数据库有着不同的连接方法,例如 cx-oracle 数据库的链接方式为: -``` +```py connection = db.connect(username, password, host, port, 'XE') ``` @@ -28,7 +28,7 @@ connection = db.connect(username, password, host, port, 'XE') In [3]: -``` +```py cursor = connection.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS orders( order_id TEXT PRIMARY KEY, @@ -46,7 +46,7 @@ connection.commit() In [4]: -``` +```py orders = [ ("A0002","2013-12-01","MSFT",1500,167.5), ("A0003","2013-12-02","GOOG",1500,167.5) @@ -59,7 +59,7 @@ connection.commit() cx-oracle 数据库使用不同的方式: -``` +```py cursor.executemany("""INSERT INTO orders VALUES (:order_id, :date, :symbol, :quantity, :price)""", orders) @@ -69,20 +69,20 @@ orders) In [5]: -``` +```py db.paramstyle ``` Out[5]: -``` +```py 'qmark' ``` 在 `query` 语句执行之后,我们需要进行 `commit`,否则数据库将不会接受这些变化,如果想撤销某个 `commit`,可以使用 `rollback()` 方法撤销到上一次 `commit()` 的结果: -``` +```py try: ... # perform some operations except: @@ -96,7 +96,7 @@ else: In [6]: -``` +```py stock = 'MSFT' cursor.execute("""SELECT * FROM orders @@ -107,7 +107,7 @@ for row in cursor: ``` -``` +```py (u'A0002', u'2013-12-01', u'MSFT', 1500, 167.5) ``` @@ -116,7 +116,7 @@ for row in cursor: In [7]: -``` +```py stock = 'AAPL' cursor.execute("""SELECT * FROM orders @@ -128,7 +128,7 @@ cursor.fetchall() Out[7]: -``` +```py [(u'A0001', u'2013-12-01', u'AAPL', 1000, 203.4)] ``` @@ -136,7 +136,7 @@ Out[7]: In [8]: -``` +```py cursor.close() connection.close() diff --git a/docs/da/070.md b/docs/da/070.md index be5c68813..25d742bcc 100644 --- a/docs/da/070.md +++ b/docs/da/070.md @@ -24,7 +24,7 @@ In [1]: -``` +```py from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Date, Float, Integer, String @@ -48,7 +48,7 @@ class Order(Base): In [2]: -``` +```py import datetime order = Order(order_id='A0004', date=datetime.date.today(), symbol='MSFT', quantity=-1000, price=187.54) @@ -58,14 +58,14 @@ order = Order(order_id='A0004', date=datetime.date.today(), symbol='MSFT', quant In [3]: -``` +```py order.get_cost() ``` Out[3]: -``` +```py -187540.0 ``` @@ -73,7 +73,7 @@ Out[3]: In [4]: -``` +```py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker @@ -87,7 +87,7 @@ session = Session() In [5]: -``` +```py session.add(order) session.commit() @@ -97,13 +97,13 @@ session.commit() In [6]: -``` +```py for row in engine.execute("SELECT * FROM orders"): print row ``` -``` +```py (u'A0001', u'2013-12-01', u'AAPL', 1000, 203.4) (u'A0002', u'2013-12-01', u'MSFT', 1500, 167.5) (u'A0003', u'2013-12-02', u'GOOG', 1500, 167.5) @@ -115,13 +115,13 @@ for row in engine.execute("SELECT * FROM orders"): In [7]: -``` +```py for order in session.query(Order).filter(Order.symbol=="AAPL"): print order.order_id, order.date, order.get_cost() ``` -``` +```py A0001 2013-12-01 203400.0 ``` @@ -130,20 +130,20 @@ A0001 2013-12-01 203400.0 In [8]: -``` +```py order_2 = session.query(Order).filter(Order.order_id=='A0002').first() ``` In [9]: -``` +```py order_2.symbol ``` Out[9]: -``` +```py u'MSFT' ``` \ No newline at end of file diff --git a/docs/da/071.md b/docs/da/071.md index 86b3e22f8..ed7ab24af 100644 --- a/docs/da/071.md +++ b/docs/da/071.md @@ -10,7 +10,7 @@ In [1]: -``` +```py def square(x): """Square of x.""" return x*x @@ -25,7 +25,7 @@ def cube(x): In [2]: -``` +```py funcs = { 'square': square, 'cube': cube, @@ -37,7 +37,7 @@ funcs = { In [3]: -``` +```py x = 2 print square(x) @@ -48,7 +48,7 @@ for func in sorted(funcs): ``` -``` +```py 4 8 cube 8 @@ -62,7 +62,7 @@ square 4 `Python` 中的函数传递方式是 `call by reference` 即引用传递,例如,对于这样的用法: -``` +```py x = [10, 11, 12] f(x) ``` @@ -71,7 +71,7 @@ f(x) In [4]: -``` +```py def mod_f(x): x[0] = 999 return x @@ -84,7 +84,7 @@ print x ``` -``` +```py [1, 2, 3] [999, 2, 3] [999, 2, 3] @@ -93,7 +93,7 @@ print x In [5]: -``` +```py def no_mod_f(x): x = [4, 5, 6] return x @@ -106,7 +106,7 @@ print x ``` -``` +```py [1, 2, 3] [4, 5, 6] [1, 2, 3] @@ -121,7 +121,7 @@ print x In [6]: -``` +```py def f(x = []): x.append(1) return x @@ -132,7 +132,7 @@ def f(x = []): In [7]: -``` +```py print f() print f() print f() @@ -142,7 +142,7 @@ print f() ``` -``` +```py [1] [1, 1] [1, 1, 1] @@ -156,7 +156,7 @@ print f() In [8]: -``` +```py def f(x = None): if x is None: x = [] @@ -172,7 +172,7 @@ print f() ``` -``` +```py [1] [1] [1] @@ -188,34 +188,34 @@ print f() `map(f, sq)` 函数将 `f` 作用到 `sq` 的每个元素上去,并返回结果组成的列表,相当于: -``` +```py [f(s) for s in sq] ``` In [9]: -``` +```py map(square, range(5)) ``` Out[9]: -``` +```py [0, 1, 4, 9, 16] ``` `filter(f, sq)` 函数的作用相当于,对于 `sq` 的每个元素 `s`,返回所有 `f(s)` 为 `True` 的 `s` 组成的列表,相当于: -``` +```py [s for s in sq if f(s)] ``` In [10]: -``` +```py def is_even(x): return x % 2 == 0 @@ -225,7 +225,7 @@ filter(is_even, range(5)) Out[10]: -``` +```py [0, 2, 4] ``` @@ -233,14 +233,14 @@ Out[10]: In [11]: -``` +```py map(square, filter(is_even, range(5))) ``` Out[11]: -``` +```py [0, 4, 16] ``` @@ -248,7 +248,7 @@ Out[11]: In [12]: -``` +```py def my_add(x, y): return x + y @@ -258,7 +258,7 @@ reduce(my_add, [1,2,3,4,5]) Out[12]: -``` +```py 15 ``` @@ -268,7 +268,7 @@ Out[12]: In [13]: -``` +```py def make_logger(target): def logger(data): with open(target, 'a') as f: @@ -283,12 +283,12 @@ foo_logger('World') In [14]: -``` +```py !cat foo.txt ``` -``` +```py Hello World @@ -296,7 +296,7 @@ World In [15]: -``` +```py import os os.remove('foo.txt') @@ -306,7 +306,7 @@ os.remove('foo.txt') 在使用 `map`, `filter`,`reduce` 等函数的时候,为了方便,对一些简单的函数,我们通常使用匿名函数的方式进行处理,其基本形式是: -``` +```py lambda : ``` @@ -314,12 +314,12 @@ lambda : In [16]: -``` +```py print map(square, range(5)) ``` -``` +```py [0, 1, 4, 9, 16] ``` @@ -328,12 +328,12 @@ print map(square, range(5)) In [17]: -``` +```py print map(lambda x: x * x, range(5)) ``` -``` +```py [0, 1, 4, 9, 16] ``` @@ -342,13 +342,13 @@ print map(lambda x: x * x, range(5)) In [18]: -``` +```py s1 = reduce(lambda x, y: x+y, map(lambda x: x**2, range(1,10))) print(s1) ``` -``` +```py 285 ``` @@ -357,13 +357,13 @@ print(s1) In [19]: -``` +```py s2 = sum(x**2 for x in range(1, 10)) print s2 ``` -``` +```py 285 ``` @@ -374,7 +374,7 @@ print s2 In [20]: -``` +```py x = 15 def print_x(): @@ -384,7 +384,7 @@ print_x() ``` -``` +```py 15 ``` @@ -393,7 +393,7 @@ print_x() In [21]: -``` +```py x = 15 def print_newx(): @@ -407,7 +407,7 @@ print x ``` -``` +```py 18 18 @@ -417,7 +417,7 @@ print x In [22]: -``` +```py x = 15 def print_newx(): @@ -430,7 +430,7 @@ print x ``` -``` +```py 18 15 @@ -444,7 +444,7 @@ Fibocacci 数列: In [23]: -``` +```py def fib1(n): """Fib with recursion.""" @@ -459,7 +459,7 @@ print [fib1(i) for i in range(10)] ``` -``` +```py [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ``` @@ -468,7 +468,7 @@ print [fib1(i) for i in range(10)] In [24]: -``` +```py def fib2(n): """Fib without recursion.""" a, b = 0, 1 @@ -480,7 +480,7 @@ print [fib2(i) for i in range(10)] ``` -``` +```py [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ``` @@ -489,13 +489,13 @@ print [fib2(i) for i in range(10)] In [25]: -``` +```py %timeit fib1(20) %timeit fib2(20) ``` -``` +```py 100 loops, best of 3: 5.35 ms per loop 100000 loops, best of 3: 2.2 µs per loop @@ -507,7 +507,7 @@ In [25]: In [26]: -``` +```py def fib3(n, cache={0: 1, 1: 1}): """Fib with recursion and caching.""" @@ -525,7 +525,7 @@ print [fib3(i) for i in range(10)] ``` -``` +```py [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 100 loops, best of 3: 5.37 ms per loop 100000 loops, best of 3: 2.19 µs per loop diff --git a/docs/da/072.md b/docs/da/072.md index c5acea82e..48ba8e462 100644 --- a/docs/da/072.md +++ b/docs/da/072.md @@ -6,7 +6,7 @@ In [1]: -``` +```py x = [2, 4, 6] for n in x: @@ -14,7 +14,7 @@ for n in x: ``` -``` +```py 2 4 6 @@ -25,7 +25,7 @@ for n in x: In [2]: -``` +```py x = [2, 4, 6] for i, n in enumerate(x): @@ -33,7 +33,7 @@ for i, n in enumerate(x): ``` -``` +```py pos 0 is 2 pos 1 is 4 pos 2 is 6 @@ -44,14 +44,14 @@ pos 2 is 6 In [3]: -``` +```py x = [2, 4, 6] i = x.__iter__() print i ``` -``` +```py ``` @@ -60,12 +60,12 @@ print i In [4]: -``` +```py print i.next() ``` -``` +```py 2 ``` @@ -74,13 +74,13 @@ print i.next() In [5]: -``` +```py print i.next() print i.next() ``` -``` +```py 4 6 @@ -88,12 +88,12 @@ print i.next() In [6]: -``` +```py i.next() ``` -``` +```py --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) in () @@ -106,13 +106,13 @@ StopIteration: In [7]: -``` +```py r = reversed(x) print r ``` -``` +```py ``` @@ -121,14 +121,14 @@ print r In [8]: -``` +```py print r.next() print r.next() print r.next() ``` -``` +```py 6 4 2 @@ -139,14 +139,14 @@ print r.next() In [9]: -``` +```py x = {'a':1, 'b':2, 'c':3} i = x.iteritems() print i ``` -``` +```py ``` @@ -155,24 +155,24 @@ print i In [10]: -``` +```py print i.__iter__() ``` -``` +```py ``` In [11]: -``` +```py print i.next() ``` -``` +```py ('a', 1) ``` @@ -183,7 +183,7 @@ print i.next() In [12]: -``` +```py class ReverseListIterator(object): def __init__(self, list): @@ -204,14 +204,14 @@ class ReverseListIterator(object): In [13]: -``` +```py x = range(10) for i in ReverseListIterator(x): print i, ``` -``` +```py 9 8 7 6 5 4 3 2 1 0 ``` @@ -220,7 +220,7 @@ for i in ReverseListIterator(x): In [14]: -``` +```py class Collatz(object): def __init__(self, start): @@ -249,13 +249,13 @@ class Collatz(object): In [15]: -``` +```py for x in Collatz(7): print x, ``` -``` +```py 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ``` @@ -264,14 +264,14 @@ for x in Collatz(7): In [16]: -``` +```py i = Collatz(7) for x, y in zip(i, i): print x, y ``` -``` +```py 22 11 34 17 52 26 @@ -287,7 +287,7 @@ for x, y in zip(i, i): In [17]: -``` +```py class BinaryTree(object): def __init__(self, value, left=None, right=None): self.value = value @@ -301,7 +301,7 @@ class BinaryTree(object): In [18]: -``` +```py class InorderIterator(object): def __init__(self, node): @@ -323,7 +323,7 @@ class InorderIterator(object): In [19]: -``` +```py tree = BinaryTree( left=BinaryTree( left=BinaryTree(1), @@ -345,13 +345,13 @@ tree = BinaryTree( In [20]: -``` +```py for value in tree: print value, ``` -``` +```py 1 2 3 4 5 6 7 8 ``` @@ -360,13 +360,13 @@ for value in tree: In [21]: -``` +```py for x,y in zip(tree, tree): print x, y ``` -``` +```py 1 1 2 2 3 3 diff --git a/docs/da/073.md b/docs/da/073.md index 9c614e552..718a76e3f 100644 --- a/docs/da/073.md +++ b/docs/da/073.md @@ -2,7 +2,7 @@ `while` 循环通常有这样的形式: -``` +```py result = [] while True: @@ -15,7 +15,7 @@ while True: 使用迭代器实现这样的循环: -``` +```py class GenericIterator(object): def __init__(self, ...): @@ -33,7 +33,7 @@ class GenericIterator(object): 更简单的,可以使用生成器: -``` +```py def generator(...): while True: @@ -51,7 +51,7 @@ def generator(...): In [1]: -``` +```py def collatz(n): sequence = [] while n != 1: @@ -67,7 +67,7 @@ for x in collatz(7): ``` -``` +```py 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ``` @@ -76,7 +76,7 @@ for x in collatz(7): In [2]: -``` +```py class Collatz(object): def __init__(self, start): self.value = start @@ -98,7 +98,7 @@ for x in Collatz(7): ``` -``` +```py 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ``` @@ -107,7 +107,7 @@ for x in Collatz(7): In [3]: -``` +```py def collatz(n): while n != 1: if n % 2 == 0: @@ -121,7 +121,7 @@ for x in collatz(7): ``` -``` +```py 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ``` @@ -130,13 +130,13 @@ for x in collatz(7): In [4]: -``` +```py x = collatz(7) print x ``` -``` +```py ``` @@ -145,13 +145,13 @@ print x In [5]: -``` +```py print x.next() print x.next() ``` -``` +```py 22 11 @@ -161,12 +161,12 @@ print x.next() In [6]: -``` +```py print x.__iter__() ``` -``` +```py ``` @@ -175,7 +175,7 @@ print x.__iter__() In [7]: -``` +```py class BinaryTree(object): def __init__(self, value, left=None, right=None): self.value = value @@ -206,7 +206,7 @@ class BinaryTree(object): In [9]: -``` +```py def inorder(self): node = self stack = [] @@ -222,7 +222,7 @@ def inorder(self): In [10]: -``` +```py tree = BinaryTree( left=BinaryTree( left=BinaryTree(1), @@ -244,7 +244,7 @@ for value in tree: ``` -``` +```py 1 2 3 4 5 6 7 8 ``` \ No newline at end of file diff --git a/docs/da/074.md b/docs/da/074.md index db7923b0b..447b768d6 100644 --- a/docs/da/074.md +++ b/docs/da/074.md @@ -1,6 +1,6 @@ # with 语句和上下文管理器 -``` +```py # create/aquire some resource ... try: @@ -18,7 +18,7 @@ finally: In [1]: -``` +```py with open('my_file', 'w') as fp: # do stuff with fp data = fp.write("Hello world") @@ -29,7 +29,7 @@ with open('my_file', 'w') as fp: In [2]: -``` +```py fp = open('my_file', 'w') try: # do stuff with f @@ -43,7 +43,7 @@ finally: 其基本用法如下: -``` +```py with : ``` @@ -52,13 +52,13 @@ with : In [3]: -``` +```py print fp.__enter__ print fp.__exit__ ``` -``` +```py @@ -70,7 +70,7 @@ print fp.__exit__ In [4]: -``` +```py class ContextManager(object): def __enter__(self): @@ -85,13 +85,13 @@ class ContextManager(object): In [5]: -``` +```py with ContextManager(): print " Inside the with statement" ``` -``` +```py Entering Inside the with statement Exiting @@ -102,19 +102,19 @@ Exiting In [6]: -``` +```py with ContextManager(): print 1/0 ``` -``` +```py Entering Exiting ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -130,7 +130,7 @@ ZeroDivisionError: integer division or modulo by zero In [7]: -``` +```py class ContextManager(object): def __enter__(self): @@ -146,13 +146,13 @@ class ContextManager(object): In [8]: -``` +```py with ContextManager() as value: print value ``` -``` +```py Entering my value Exiting @@ -163,21 +163,21 @@ Exiting In [9]: -``` +```py fp = open('my_file', 'r') print fp.__enter__() fp.close() ``` -``` +```py ``` In [10]: -``` +```py import os os.remove('my_file') @@ -187,7 +187,7 @@ os.remove('my_file') In [11]: -``` +```py class ContextManager(object): def __enter__(self): @@ -201,13 +201,13 @@ class ContextManager(object): In [12]: -``` +```py with ContextManager() as value: print value ``` -``` +```py Entering <__main__.ContextManager object at 0x0000000003D48828> Exiting @@ -220,7 +220,7 @@ Exiting In [13]: -``` +```py class ContextManager(object): def __enter__(self): @@ -237,20 +237,20 @@ class ContextManager(object): In [14]: -``` +```py with ContextManager(): print 1/0 ``` -``` +```py Entering Exiting Exception: integer division or modulo by zero ``` -``` +```py --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) in () @@ -264,7 +264,7 @@ ZeroDivisionError: integer division or modulo by zero In [15]: -``` +```py class ContextManager(object): def __enter__(self): @@ -280,13 +280,13 @@ class ContextManager(object): In [16]: -``` +```py with ContextManager(): print 1/0 ``` -``` +```py Entering Exiting Exception suppresed: integer division or modulo by zero @@ -301,7 +301,7 @@ Exiting In [17]: -``` +```py class Transaction(object): def __init__(self, connection): @@ -324,7 +324,7 @@ class Transaction(object): In [18]: -``` +```py import sqlite3 as db connection = db.connect(":memory:") @@ -344,7 +344,7 @@ with Transaction(connection) as cursor: In [19]: -``` +```py with Transaction(connection) as cursor: cursor.executemany("""INSERT OR REPLACE INTO addresses VALUES (?, ?, ?, ?, ?, ?)""", [ (0, '515 Congress Ave', 'Austin', 'Texas', 'USA', '78701'), @@ -359,7 +359,7 @@ with Transaction(connection) as cursor: In [20]: -``` +```py with Transaction(connection) as cursor: cursor.execute("""INSERT OR REPLACE INTO addresses VALUES (?, ?, ?, ?, ?, ?)""", (4, '2100 Pennsylvania Ave', 'Washington', 'DC', 'USA', '78701'), @@ -368,7 +368,7 @@ with Transaction(connection) as cursor: ``` -``` +```py --------------------------------------------------------------------------- Exception Traceback (most recent call last) in () @@ -383,14 +383,14 @@ Exception: out of addresses In [21]: -``` +```py cursor.execute("SELECT * FROM addresses") for row in cursor: print row ``` -``` +```py (0, u'515 Congress Ave', u'Austin', u'Texas', u'USA', u'78701') (1, u'245 Park Avenue', u'New York', u'New York', u'USA', u'10167') (2, u'21 J.J. Thompson Ave.', u'Cambridge', None, u'UK', u'CB3 0FA') @@ -406,7 +406,7 @@ for row in cursor: In [23]: -``` +```py from contextlib import closing import urllib @@ -417,7 +417,7 @@ print html[:100] ``` -``` +```py ``` @@ -23,14 +23,14 @@ print(type(foo)) In [2]: -``` +```py dir(foo) ``` Out[2]: -``` +```py ['__call__', '__class__', '__closure__', @@ -68,12 +68,12 @@ Out[2]: In [3]: -``` +```py foo.__call__(42) ``` -``` +```py 42 ``` @@ -82,12 +82,12 @@ foo.__call__(42) In [4]: -``` +```py foo(42) ``` -``` +```py 42 ``` @@ -96,7 +96,7 @@ foo(42) In [5]: -``` +```py def bar(f, x): x += 1 f(x) @@ -105,12 +105,12 @@ def bar(f, x): In [6]: -``` +```py bar(foo, 4) ``` -``` +```py 5 ``` @@ -121,7 +121,7 @@ bar(foo, 4) In [7]: -``` +```py def dec(f): print 'I am decorating function', id(f) return f @@ -132,12 +132,12 @@ def dec(f): In [8]: -``` +```py declen = dec(len) ``` -``` +```py I am decorating function 33716168 ``` @@ -146,14 +146,14 @@ I am decorating function 33716168 In [9]: -``` +```py declen([10,20,30]) ``` Out[9]: -``` +```py 3 ``` @@ -161,7 +161,7 @@ Out[9]: In [10]: -``` +```py def loud(f): def new_func(*args, **kw): print 'calling with', args, kw @@ -174,19 +174,19 @@ def loud(f): In [11]: -``` +```py loudlen = loud(len) ``` In [12]: -``` +```py loudlen([10, 20, 30]) ``` -``` +```py calling with ([10, 20, 30],) {} return value is 3 @@ -194,7 +194,7 @@ return value is 3 Out[12]: -``` +```py 3 ``` @@ -206,7 +206,7 @@ Out[12]: In [13]: -``` +```py def foo(x): print x @@ -214,7 +214,7 @@ foo = dec(foo) ``` -``` +```py I am decorating function 64021672 ``` @@ -223,21 +223,21 @@ I am decorating function 64021672 In [14]: -``` +```py @dec def foo(x): print x ``` -``` +```py I am decorating function 64021112 ``` 事实上,如果修饰符返回的是一个函数,那么可以链式的使用修饰符: -``` +```py @dec1 @dec2 def foo(x): @@ -249,7 +249,7 @@ def foo(x): In [15]: -``` +```py @loud def foo(x): print x @@ -258,12 +258,12 @@ def foo(x): In [16]: -``` +```py foo(42) ``` -``` +```py calling with (42,) {} 42 return value is None @@ -276,7 +276,7 @@ return value is None In [17]: -``` +```py def plus_one(f): def new_func(x): return f(x) + 1 @@ -293,7 +293,7 @@ def times_two(f): In [18]: -``` +```py @plus_one @times_two def foo(x): @@ -303,14 +303,14 @@ def foo(x): In [19]: -``` +```py foo(13) ``` Out[19]: -``` +```py 27 ``` @@ -320,7 +320,7 @@ Out[19]: In [20]: -``` +```py def super_dec(x, y, z): def dec(f): def new_func(*args, **kw): @@ -335,7 +335,7 @@ def super_dec(x, y, z): In [21]: -``` +```py def super_loud(filename): fp = open(filename, 'w') def loud(f): @@ -355,7 +355,7 @@ def super_loud(filename): In [22]: -``` +```py @super_loud('test.txt') def foo(x): print x @@ -366,12 +366,12 @@ def foo(x): In [23]: -``` +```py foo(12) ``` -``` +```py 12 ``` @@ -380,20 +380,20 @@ foo(12) In [24]: -``` +```py with open('test.txt') as fp: print fp.read() ``` -``` +```py calling with(12,){} ``` In [25]: -``` +```py import os os.remove('test.txt') diff --git a/docs/da/076.md b/docs/da/076.md index add946806..de5ada182 100644 --- a/docs/da/076.md +++ b/docs/da/076.md @@ -6,7 +6,7 @@ In [1]: -``` +```py class Foo(object): @classmethod def bar(cls, x): @@ -21,12 +21,12 @@ class Foo(object): In [2]: -``` +```py Foo.bar(12) ``` -``` +```py the input is 12 ``` @@ -37,7 +37,7 @@ the input is 12 In [3]: -``` +```py class Foo(object): def __init__(self, data): self.data = data @@ -52,7 +52,7 @@ class Foo(object): In [4]: -``` +```py foo = Foo(23) foo.x @@ -60,7 +60,7 @@ foo.x Out[4]: -``` +```py 23 ``` @@ -68,12 +68,12 @@ Out[4]: In [5]: -``` +```py foo.x = 1 ``` -``` +```py --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () @@ -86,7 +86,7 @@ AttributeError: can't set attribute In [6]: -``` +```py class Foo(object): def __init__(self, data): self.data = data @@ -103,13 +103,13 @@ class Foo(object): In [7]: -``` +```py foo = Foo(23) print foo.x ``` -``` +```py 23 ``` @@ -118,13 +118,13 @@ print foo.x In [8]: -``` +```py foo.x = 1 print foo.x ``` -``` +```py 1 ``` @@ -135,7 +135,7 @@ print foo.x In [9]: -``` +```py from numpy import vectorize, arange @vectorize @@ -151,7 +151,7 @@ f(arange(-10.0,10.0)) Out[9]: -``` +```py array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ``` @@ -162,7 +162,7 @@ array([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0., In [10]: -``` +```py class Registry(object): def __init__(self): self._data = {} @@ -180,7 +180,7 @@ class Registry(object): In [11]: -``` +```py registry = Registry() ``` @@ -189,7 +189,7 @@ registry = Registry() In [12]: -``` +```py @registry.register def greeting(): print "hello world" @@ -200,27 +200,27 @@ def greeting(): In [13]: -``` +```py registry._data ``` Out[13]: -``` +```py {'greeting': } ``` In [14]: -``` +```py registry.greeting ``` Out[14]: -``` +```py ``` @@ -232,7 +232,7 @@ Out[14]: In [15]: -``` +```py def logging_call(f): def wrapper(*a, **kw): print 'calling {}'.format(f.__name__) @@ -250,7 +250,7 @@ print square.__doc__, square.__name__ ``` -``` +```py None wrapper ``` @@ -261,7 +261,7 @@ None wrapper In [16]: -``` +```py import functools def logging_call(f): @@ -282,7 +282,7 @@ print square.__doc__, square.__name__ ``` -``` +```py square function. square diff --git a/docs/da/077.md b/docs/da/077.md index b2267cade..bf2fb046d 100644 --- a/docs/da/077.md +++ b/docs/da/077.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import operator as op ``` @@ -15,12 +15,12 @@ import operator as op In [2]: -``` +```py print reduce(op.add, range(10)) ``` -``` +```py 45 ``` @@ -29,12 +29,12 @@ print reduce(op.add, range(10)) In [3]: -``` +```py print reduce(op.mul, range(1,10)) ``` -``` +```py 362880 ``` @@ -43,7 +43,7 @@ print reduce(op.mul, range(1,10)) In [4]: -``` +```py my_list = [('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)] # 标准排序 @@ -57,7 +57,7 @@ print sorted(my_list, key=lambda x: len(x[0])) ``` -``` +```py [('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)] [('a', 1), ('ccc', 2), ('dddd', 3), ('bb', 4)] [('a', 1), ('bb', 4), ('ccc', 2), ('dddd', 3)] @@ -70,7 +70,7 @@ print sorted(my_list, key=lambda x: len(x[0])) In [5]: -``` +```py from functools import partial # 将 reduce 的第一个参数指定为加法,得到的是类似求和的函数 @@ -84,7 +84,7 @@ print prod_([1,2,3,4]) ``` -``` +```py 10 24 @@ -98,7 +98,7 @@ print prod_([1,2,3,4]) In [6]: -``` +```py from itertools import cycle, groupby, islice, permutations, combinations ``` @@ -107,12 +107,12 @@ from itertools import cycle, groupby, islice, permutations, combinations In [7]: -``` +```py print list(islice(cycle('abcd'), 0, 10)) ``` -``` +```py ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b'] ``` @@ -121,7 +121,7 @@ print list(islice(cycle('abcd'), 0, 10)) In [8]: -``` +```py animals = sorted(['pig', 'cow', 'giraffe', 'elephant', 'dog', 'cat', 'hippo', 'lion', 'tiger'], key=len) @@ -132,7 +132,7 @@ print ``` -``` +```py 3 ['pig', 'cow', 'dog', 'cat'] 4 ['lion'] 5 ['hippo', 'tiger'] @@ -145,12 +145,12 @@ print In [9]: -``` +```py print [''.join(p) for p in permutations('abc')] ``` -``` +```py ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] ``` @@ -159,12 +159,12 @@ print [''.join(p) for p in permutations('abc')] In [10]: -``` +```py print [list(c) for c in combinations([1,2,3,4], r=2)] ``` -``` +```py [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] ``` diff --git a/docs/da/078.md b/docs/da/078.md index 94bddf13e..bdcacd98d 100644 --- a/docs/da/078.md +++ b/docs/da/078.md @@ -13,7 +13,7 @@ In [1]: -``` +```py def foo(a,b): c = 1 d = a + b + c @@ -26,7 +26,7 @@ def foo(a,b): In [2]: -``` +```py c = 1 def foo(a,b): d = a + b + c @@ -41,7 +41,7 @@ def foo(a,b): In [3]: -``` +```py c = 1 def foo(): global c @@ -53,7 +53,7 @@ print c ``` -``` +```py 1 2 @@ -65,7 +65,7 @@ print c In [4]: -``` +```py c = 1 def foo(): c = 2 @@ -76,7 +76,7 @@ print c ``` -``` +```py 1 1 @@ -86,7 +86,7 @@ print c In [5]: -``` +```py def list_length(a): return len(a) @@ -95,7 +95,7 @@ print list_length(a) ``` -``` +```py 3 ``` @@ -104,7 +104,7 @@ print list_length(a) In [6]: -``` +```py import __builtin__ __builtin__.len @@ -113,7 +113,7 @@ __builtin__.len Out[6]: -``` +```py ``` @@ -128,7 +128,7 @@ Out[6]: In [7]: -``` +```py # global var = 0 @@ -162,7 +162,7 @@ class MyClass(object): In [8]: -``` +```py obj = MyClass() ``` @@ -180,12 +180,12 @@ obj = MyClass() In [9]: -``` +```py obj.access_class_c() ``` -``` +```py class var: 1 ``` @@ -203,12 +203,12 @@ class var: 1 In [10]: -``` +```py obj.access_global_c() ``` -``` +```py global var: 0 ``` @@ -226,12 +226,12 @@ global var: 0 In [11]: -``` +```py obj.write_class_c() ``` -``` +```py class var: 2 ``` @@ -249,26 +249,26 @@ class var: 2 In [12]: -``` +```py obj.write_instance_c() ``` -``` +```py instance var: 3 ``` In [13]: -``` +```py MyClass.var ``` Out[13]: -``` +```py 2 ``` @@ -280,7 +280,7 @@ Out[13]: In [14]: -``` +```py def outer(): a = 1 def inner(): @@ -291,7 +291,7 @@ outer() ``` -``` +```py a = 1 ``` @@ -302,7 +302,7 @@ a = 1 In [15]: -``` +```py def outer(): a = 1 def inner(): @@ -315,7 +315,7 @@ print 'a (1):', func() ``` -``` +```py a (1): 1 ``` diff --git a/docs/da/079.md b/docs/da/079.md index 07b29eb33..ac5bcdb04 100644 --- a/docs/da/079.md +++ b/docs/da/079.md @@ -4,7 +4,7 @@ 对于 **C** 语言,代码一般要先编译,再执行。 -``` +```py .c -> .exe ``` @@ -12,7 +12,7 @@ shell 脚本 -``` +```py .sh -> interpreter ``` @@ -20,13 +20,13 @@ shell 脚本 **Python, Java** 等语言先将代码编译为 byte code(不是机器码),然后再处理: -``` +```py .py -> .pyc -> interpreter ``` ## eval 函数 -``` +```py eval(statement, glob, local) ``` @@ -34,7 +34,7 @@ eval(statement, glob, local) In [1]: -``` +```py a = 1 eval("a+1") @@ -43,7 +43,7 @@ eval("a+1") Out[1]: -``` +```py 2 ``` @@ -51,7 +51,7 @@ Out[1]: In [2]: -``` +```py local = dict(a=2) glob = {} eval("a+1", glob, local) @@ -60,7 +60,7 @@ eval("a+1", glob, local) Out[2]: -``` +```py 3 ``` @@ -68,7 +68,7 @@ Out[2]: ## exec 函数 -``` +```py exec(statement, glob, local) ``` @@ -76,7 +76,7 @@ exec(statement, glob, local) In [3]: -``` +```py a = 1 exec("b = a+1") @@ -85,14 +85,14 @@ print b ``` -``` +```py 2 ``` In [4]: -``` +```py local = dict(a=2) glob = {} exec("b = a+1", glob, local) @@ -101,7 +101,7 @@ print local ``` -``` +```py {'a': 2, 'b': 3} ``` @@ -114,13 +114,13 @@ print local ## compile 函数生成 byte code -``` +```py compile(str, filename, mode) ``` In [5]: -``` +```py a = 1 c = compile("a+2", "", 'eval') @@ -130,13 +130,13 @@ eval(c) Out[5]: -``` +```py 3 ``` In [6]: -``` +```py a = 1 c = compile("b=a+2", "", 'exec') @@ -147,7 +147,7 @@ b Out[6]: -``` +```py 3 ``` @@ -155,14 +155,14 @@ Out[6]: In [7]: -``` +```py import ast ``` In [8]: -``` +```py tree = ast.parse("a+2", "", "eval") ast.dump(tree) @@ -171,7 +171,7 @@ ast.dump(tree) Out[8]: -``` +```py "Expression(body=BinOp(left=Name(id='a', ctx=Load()), op=Add(), right=Num(n=2)))" ``` @@ -179,7 +179,7 @@ Out[8]: In [9]: -``` +```py tree.body.right.n = 3 ast.dump(tree) @@ -188,13 +188,13 @@ ast.dump(tree) Out[9]: -``` +```py "Expression(body=BinOp(left=Name(id='a', ctx=Load()), op=Add(), right=Num(n=3)))" ``` In [10]: -``` +```py a = 1 c = compile(tree, '', 'eval') @@ -204,7 +204,7 @@ eval(c) Out[10]: -``` +```py 4 ``` @@ -212,13 +212,13 @@ Out[10]: In [11]: -``` +```py ast.literal_eval("[10.0, 2, True, 'foo']") ``` Out[11]: -``` +```py [10.0, 2, True, 'foo'] ``` \ No newline at end of file diff --git a/docs/da/081.md b/docs/da/081.md index 3ea4aef43..5e439f436 100644 --- a/docs/da/081.md +++ b/docs/da/081.md @@ -12,7 +12,7 @@ In [1]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -39,7 +39,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py %matplotlib inline ``` @@ -52,7 +52,7 @@ In [2]: In [3]: -``` +```py plt.plot([1,2,3,4]) plt.ylabel('some numbers') @@ -188,14 +188,14 @@ JElHsGOQJB3BjkGSdAQ7BknSEewYJElHsGOQJB3BjkGSdIT/DyxDilXU3HwUAAAAAElFTkSuQmCC In [4]: -``` +```py plt.plot([1,2,3,4], [1,4,9,16]) ``` Out[4]: -``` +```py [] ``` @@ -328,7 +328,7 @@ SaoBg7kk1YDBXJJqwGAuSTVgMJekGvhf3kAwE/Ra4D0AAAAASUVORK5CYII= In [5]: -``` +```py plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.show() @@ -414,13 +414,13 @@ DHNJaoBhLkkNMMwlqQGGuSQ14P8AGTGlG2xI8vsAAAAASUVORK5CYII= 与 **`MATLAB`** 类似,这里可以使用 `axis` 函数指定坐标轴显示的范围: -``` +```py plt.axis([xmin, xmax, ymin, ymax]) ``` In [6]: -``` +```py plt.plot([1,2,3,4], [1,4,9,16], 'ro') # 指定 x 轴显示区域为 0-6,y 轴为 0-20 plt.axis([0,6,0,20]) @@ -498,7 +498,7 @@ gGQINwAkQ7gBIBnCDQDJEG4ASIZwA0Ay/wc0fnnqj1dLcQAAAABJRU5ErkJggg== In [7]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -634,7 +634,7 @@ dEkqCANdkgrCQJekgjDQJakgDHRJKggDXZIK4v8D3/l7N0FXwlcAAAAASUVORK5CYII= In [8]: -``` +```py x = np.linspace(-np.pi,np.pi) y = np.sin(x) @@ -830,7 +830,7 @@ fxeZmr/ZF8WeAAAAAElFTkSuQmCC In [9]: -``` +```py # 加逗号 line 中得到的是 line2D 对象,不加逗号得到的是只有一个 line2D 对象的列表 line, = plt.plot(x, y, 'r-') @@ -930,7 +930,7 @@ Jyfj1DY0XlkAAAAASUVORK5CYII= In [10]: -``` +```py lines = plt.plot(x, y) # 使用键值对 @@ -1117,12 +1117,12 @@ fxeZmr/ZF8WeAAAAAElFTkSuQmCC In [11]: -``` +```py plt.setp(lines) ``` -``` +```py agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False] @@ -1172,7 +1172,7 @@ plt.setp(lines) `figure()` 函数会产生一个指定编号为 `num` 的图: -``` +```py plt.figure(num) ``` @@ -1180,7 +1180,7 @@ plt.figure(num) 使用 `subplot` 可以在一副图中生成多个子图,其参数为: -``` +```py plt.subplot(numrows, numcols, fignum) ``` @@ -1188,7 +1188,7 @@ plt.subplot(numrows, numcols, fignum) In [12]: -``` +```py def f(t): return np.exp(-t) * np.cos(2*np.pi*t) @@ -1504,7 +1504,7 @@ SXD+P5ePy54P9ccKAAAAAElFTkSuQmCC In [13]: -``` +```py mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) @@ -1738,7 +1738,7 @@ y8vMzDrCDYqZmXWEGxQzM+sINyhmZtYRblDMzKwj3KCYmVlHuEExM7OOcINiZmYd8f8BVKt7L24G In [14]: -``` +```py ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) diff --git a/docs/da/082.md b/docs/da/082.md index b1376c7eb..fed2833c2 100644 --- a/docs/da/082.md +++ b/docs/da/082.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import matplotlib.pyplot as plt import numpy as np @@ -14,20 +14,20 @@ import numpy as np In [2]: -``` +```py plt.style.available ``` Out[2]: -``` +```py [u'dark_background', u'bmh', u'grayscale', u'ggplot', u'fivethirtyeight'] ``` In [3]: -``` +```py x = np.linspace(0, 2 * np.pi) y = np.sin(x) @@ -199,7 +199,7 @@ gg== In [4]: -``` +```py plt.style.use('ggplot') plt.plot(x, y) @@ -397,7 +397,7 @@ wU9EFGT+Pxvu78Bmq8eQAAAAAElFTkSuQmCC In [5]: -``` +```py with plt.style.context(('dark_background')): plt.plot(x, y, 'r-o') plt.show() @@ -564,7 +564,7 @@ SUVORK5CYII= In [6]: -``` +```py with plt.style.context(('dark_background')): pass plt.plot(x, y, 'r-o') @@ -764,7 +764,7 @@ YeEnIgoyLPxEREHm/wEVP/FL2qENYwAAAABJRU5ErkJggg== In [7]: -``` +```py plt.style.use(['dark_background', 'ggplot']) plt.plot(x, y, 'r-o') @@ -968,7 +968,7 @@ YeEnIgoyLPxEREHm/wEVP/FL2qENYwAAAABJRU5ErkJggg== In [8]: -``` +```py import matplotlib matplotlib.get_configdir() @@ -976,13 +976,13 @@ matplotlib.get_configdir() Out[8]: -``` +```py u'c:/Users/Jin\\.matplotlib' ``` 里面的内容以 `属性:值` 的形式保存: -``` +```py axes.titlesize : 24 axes.labelsize : 20 lines.linewidth : 3 @@ -993,6 +993,6 @@ ytick.labelsize : 16 假设我们将其保存为 `mpl_configdir/stylelib/presentation.mplstyle`,那么使用这个风格的时候只需要调用: -``` +```py plt.style.use('presentation') ``` \ No newline at end of file diff --git a/docs/da/083.md b/docs/da/083.md index 30042193c..b2ed940ab 100644 --- a/docs/da/083.md +++ b/docs/da/083.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import matplotlib.pyplot as plt import numpy as np %matplotlib inline @@ -25,7 +25,7 @@ import numpy as np In [2]: -``` +```py # -*- coding: utf-8 -*- import matplotlib.pyplot as plt %matplotlib inline @@ -551,7 +551,7 @@ YvJMRERERGQiJs9ERERERCZi8kxEREREZCImz0REREREJvofHWbt2xvCuI0AAAAASUVORK5CYII= In [3]: -``` +```py import matplotlib.pyplot as plt import matplotlib.patches as patches @@ -980,7 +980,7 @@ Qwz4kiRJUkMM+JIkSVJDDPiSJElSQwz4kiRJUkMM+JIkSVJDDPiSJElSQwz4kiRJUkMM+JIkSVJD In [4]: -``` +```py fig = plt.figure() ax = fig.add_subplot(111) @@ -1265,7 +1265,7 @@ RVGUgPP/Qde6gvF4TtQAAAAASUVORK5CYII= In [5]: -``` +```py fig = plt.figure() ax = fig.add_subplot(111) @@ -1536,7 +1536,7 @@ cNwO3SiKoig2o45eURQl4KijVxRFCTjq6BVFUQKOOnpFUZSAo45eURQl4KijVxRFCTjq6BVFUQLO In [6]: -``` +```py fig = plt.figure() ax = fig.add_subplot(111, polar=True) r = np.arange(0,1,0.001) diff --git a/docs/da/084.md b/docs/da/084.md index d6a9f1cc5..ed3a148f6 100644 --- a/docs/da/084.md +++ b/docs/da/084.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import matplotlib.pyplot as plt import numpy as np %matplotlib inline @@ -13,7 +13,7 @@ import numpy as np In [2]: -``` +```py # plain text plt.title('alpha > beta') @@ -100,7 +100,7 @@ a4E7gD3AZVXVXLiP+Jr4CHB5ktvpD0TfV1UPrVjRyyjJZ4FTgDVJtgMX0Z+iW3JuehOTJDXIP7Mn SQ0y3CWpQYa7JDXIcJekBhnuktQgw12SGmS4S1KDDHdJatD/A8TB+T0A8shJAAAAAElFTkSuQmCC )In [3]: -``` +```py # math text plt.title(r'$\alpha > \beta$') @@ -185,13 +185,13 @@ uyQ1ZNwlqSHjLkkNGXdJasi4S1JDxl2SGvp/zy4/4DuVo0MAAAAASUVORK5CYII= $\alpha_i > \beta_i$: -``` +```py r'$\alpha_i > \beta_i$' ``` $\sum\limits_{i=0}^\infty x_i$: -``` +```py r'$\sum_{i=0}^\infty x_i$' ``` @@ -204,13 +204,13 @@ r'$\sum_{i=0}^\infty x_i$' $\frac{3}{4}, \binom{3}{4}, \stackrel{3}{4}$: -``` +```py r'$\frac{3}{4}, \binom{3}{4}, \stackrel{3}{4}$' ``` $\frac{5 - \frac{1}{x}}{4}$: -``` +```py r'$\frac{5 - \frac{1}{x}}{4}$' ``` @@ -218,13 +218,13 @@ r'$\frac{5 - \frac{1}{x}}{4}$' $(\frac{5 - \frac{1}{x}}{4})$ -``` +```py r'$(\frac{5 - \frac{1}{x}}{4})$' ``` $\left(\frac{5 - \frac{1}{x}}{4}\right)$: -``` +```py r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$' ``` @@ -232,13 +232,13 @@ r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$' $\sqrt{2}$: -``` +```py r'$\sqrt{2}$' ``` $\sqrt[3]{x}$: -``` +```py r'$\sqrt[3]{x}$' ``` @@ -258,7 +258,7 @@ r'$\sqrt[3]{x}$' $s(t) = \mathcal{A}\ \sin(2 \omega t)$: -``` +```py s(t) = \mathcal{A}\ \sin(2 \omega t) ``` @@ -292,7 +292,7 @@ s(t) = \mathcal{A}\ \sin(2 \omega t) In [4]: -``` +```py import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 2.0, 0.01) diff --git a/docs/da/085.md b/docs/da/085.md index d8686ea5f..5d8661ae9 100644 --- a/docs/da/085.md +++ b/docs/da/085.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np @@ -20,21 +20,21 @@ import numpy as np In [2]: -``` +```py img = mpimg.imread('stinkbug.png') ``` In [3]: -``` +```py img.shape ``` Out[3]: -``` +```py (375L, 500L, 3L) ``` @@ -42,14 +42,14 @@ Out[3]: In [4]: -``` +```py img.dtype ``` Out[4]: -``` +```py dtype('float32') ``` @@ -59,7 +59,7 @@ dtype('float32') In [5]: -``` +```py imgplot = plt.imshow(img) ``` @@ -929,7 +929,7 @@ dJpO02l6yukUWE/TaTpNp+kpp/8PTYoQ8rA9sPAAAAAASUVORK5CYII= In [6]: -``` +```py lum_img = img[:,:,0] imgplot = plt.imshow(lum_img) @@ -2561,7 +2561,7 @@ bLPNbtg2YN1ss802u2HbgHWzzTbb7IZtA9bNNttssxu2DVg322yzzW7YNmDdbLPNNrth24B1s802 In [7]: -``` +```py imgplot = plt.imshow(lum_img) imgplot.set_cmap('hot') @@ -3678,7 +3678,7 @@ bbktt+V2idsysC635bbcltslbsvAutyW23Jbbpe4LQPrcltuy225XeK2DKzLbbktt+V2idsysC63 5bbcltslbsvAutyW23Jbbpe4/X9nGwcxiuGaUwAAAABJRU5ErkJggg== )In [8]: -``` +```py imgplot = plt.imshow(lum_img) imgplot.set_cmap('spectral') @@ -5284,7 +5284,7 @@ dVZmZVZm5RKXGbDOyqzMyqxc4jID1lmZlVmZlUtc/h8Kz3lJYE3qlwAAAABJRU5ErkJggg== In [9]: -``` +```py imgplot = plt.imshow(lum_img) imgplot.set_cmap('spectral') plt.colorbar() @@ -6700,7 +6700,7 @@ RK5CYII= In [10]: -``` +```py plt.hist(lum_img.flatten(), 256, range=(0.0,1.0), fc='k', ec='k') plt.show() @@ -6794,7 +6794,7 @@ U8BgkCQ1DAZJUsNgkCQ1DAZJUsNgkCQ1DAZJUsNgkCQ1/g/zoP/h/mn/wgAAAABJRU5ErkJggg== In [11]: -``` +```py imgplot = plt.imshow(lum_img) imgplot.set_clim(0.0,0.7) @@ -8186,7 +8186,7 @@ btWA5gcAAAAASUVORK5CYII= In [12]: -``` +```py from PIL import Image img = Image.open('stinkbug.png') rsize = img.resize((img.size[0]/10,img.size[1]/10)) @@ -8635,7 +8635,7 @@ gPz/QCjzUOP0/xAAAAAASUVORK5CYII= In [13]: -``` +```py imgplot = plt.imshow(rsizeArr) imgplot.set_interpolation('nearest') @@ -8770,7 +8770,7 @@ OgD/ZGY3nQn7W4m6O4qIRFAPHhGRCEqWIiIRlCxFRCIoWYqIRFCyFBGJoGQpIhJByVJEJIKSpYhI hP8H0Tz8GZcurRgAAAAASUVORK5CYII= )In [14]: -``` +```py imgplot = plt.imshow(rsizeArr) imgplot.set_interpolation('bicubic') diff --git a/docs/da/086.md b/docs/da/086.md index ec36ebe20..d2ae139cf 100644 --- a/docs/da/086.md +++ b/docs/da/086.md @@ -6,7 +6,7 @@ In [1]: -``` +```py import numpy.random import matplotlib.pyplot as plt %matplotlib inline @@ -353,7 +353,7 @@ RU5ErkJggg== `text()` 函数接受 `bbox` 参数来绘制文本框。 -``` +```py bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2) t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, size=15, @@ -363,7 +363,7 @@ t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45, 可以这样来获取这个文本框,并对其参数进行修改: -``` +```py bb = t.get_bbox_patch() bb.set_boxstyle("rarrow", pad=0.6) @@ -383,7 +383,7 @@ bb.set_boxstyle("rarrow", pad=0.6) In [2]: -``` +```py import matplotlib.patches as mpatch import matplotlib.pyplot as plt @@ -805,7 +805,7 @@ RK5CYII= In [3]: -``` +```py plt.figure(1, figsize=(3,3)) ax = plt.subplot(111) @@ -884,7 +884,7 @@ s0T+b9hmiRyPWSLHY5bI8ZglcjxmiRyPWSLHY5bo/3ysOsDVDV6UAAAAAElFTkSuQmCC In [4]: -``` +```py import matplotlib.pyplot as plt import matplotlib.patches as mpatches @@ -1194,7 +1194,7 @@ o4aCEEIIIQn7f35zqmEqULpsAAAAAElFTkSuQmCC In [5]: -``` +```py import matplotlib.pyplot as plt import matplotlib.patches as mpatches @@ -1818,7 +1818,7 @@ o4KCEEIIIRqjgoIQQgghGvt/FlbD4KMSO5AAAAAASUVORK5CYII= In [6]: -``` +```py import matplotlib.patches as mpatches import matplotlib.pyplot as plt diff --git a/docs/da/087.md b/docs/da/087.md index 190717a6c..fdd438ce7 100644 --- a/docs/da/087.md +++ b/docs/da/087.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt @@ -22,7 +22,7 @@ import matplotlib.pyplot as plt 调用 `legend()` 会自动获取当前的 `Axes` 对象,并且得到这些 handles 和 labels,相当于: -``` +```py handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels) ``` @@ -31,7 +31,7 @@ ax.legend(handles, labels) In [2]: -``` +```py line_up, = plt.plot([1,2,3], label='Line 2') line_down, = plt.plot([3,2,1], label='Line 1') plt.legend(handles=[line_up, line_down]) @@ -143,7 +143,7 @@ AAAAAElFTkSuQmCC In [3]: -``` +```py line_up, = plt.plot([1,2,3]) line_down, = plt.plot([3,2,1]) plt.legend([line_up, line_down], ['Line Up', 'Line Down']) @@ -270,7 +270,7 @@ DBM7ACQMEzsAJAwTOwAkDBM7ACQMEzsAJMz/A0F5tMDKB4A7AAAAAElFTkSuQmCC In [4]: -``` +```py import matplotlib.patches as mpatches red_patch = mpatches.Patch(color='red', label='The red data') @@ -370,7 +370,7 @@ yHCXpAIZ7pJUIMNdkgpkuEtSgQx3SSqQ4S5JBfp/m91y2WTXKGoAAAAASUVORK5CYII= In [5]: -``` +```py import matplotlib.lines as mlines import matplotlib.pyplot as plt @@ -481,7 +481,7 @@ EFOmWk0euQAAAABJRU5ErkJggg== In [6]: -``` +```py plt.plot([1,2,3], label="test1") plt.plot([3,2,1], label="test2") plt.legend(bbox_to_anchor=(1, 1), @@ -601,7 +601,7 @@ VsmYJAjFAAAAAElFTkSuQmCC In [7]: -``` +```py plt.subplot(211) plt.plot([1,2,3], label="test1") plt.plot([3,2,1], label="test2") @@ -799,7 +799,7 @@ EZtHunC15QAAAABJRU5ErkJggg== In [8]: -``` +```py line1, = plt.plot([1,2,3], label="Line 1", linestyle='--') line2, = plt.plot([3,2,1], label="Line 2", linewidth=4) @@ -956,7 +956,7 @@ DgApQ2IHgJQhsQNAyvw/a8UJ8l9tWroAAAAASUVORK5CYII= In [9]: -``` +```py from numpy.random import randn z = randn(10) @@ -1127,7 +1127,7 @@ Be7/A4OqIDdoxkFmAAAAAElFTkSuQmCC In [10]: -``` +```py import matplotlib.pyplot as plt import matplotlib.patches as mpatches @@ -1251,7 +1251,7 @@ IMNdkgr0v4W1q8xEcgEdAAAAAElFTkSuQmCC In [11]: -``` +```py from matplotlib.legend_handler import HandlerPatch import matplotlib.pyplot as plt import matplotlib.patches as mpatches diff --git a/docs/da/088.md b/docs/da/088.md index 4850e16f7..3c0cfa29f 100644 --- a/docs/da/088.md +++ b/docs/da/088.md @@ -33,7 +33,7 @@ In [1]: -``` +```py %pylab inline subplot(2,1,1) @@ -48,7 +48,7 @@ show() ``` -``` +```py Populating the interactive namespace from numpy and matplotlib ``` @@ -194,7 +194,7 @@ AABJRU5ErkJggg== In [2]: -``` +```py import matplotlib.gridspec as gridspec G = gridspec.GridSpec(3, 3) @@ -403,7 +403,7 @@ tAAAAABJRU5ErkJggg== In [3]: -``` +```py axes([0.1,0.1,.8,.8]) xticks([]), yticks([]) text(0.6,0.6, 'axes([0.1,0.1,.8,.8])',ha='center',va='center',size=20,alpha=.5) @@ -561,7 +561,7 @@ w5mISEAMZyIiATGciYgExHAmIhIQw5mISEAMZyIiATGciYgExHAmIhKQ240KyGSy29EOIiK6hsxm s93pNhAR0Rgc1iAiEhDDmYhIQAxnIiIBMZyJiATEcCYiEtD/AVGhDgsTjgbFAAAAAElFTkSuQmCC )In [4]: -``` +```py axes([0.1,0.1,.5,.5]) xticks([]), yticks([]) text(0.1,0.1, 'axes([0.1,0.1,.8,.8])',ha='left',va='center',size=16,alpha=.5) diff --git a/docs/da/089.md b/docs/da/089.md index 57000c686..332ff87e9 100644 --- a/docs/da/089.md +++ b/docs/da/089.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -14,7 +14,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py x = np.linspace(-np.pi, np.pi) c, s = np.cos(x), np.sin(x) @@ -24,7 +24,7 @@ c, s = np.cos(x), np.sin(x) In [3]: -``` +```py %matplotlib inline # 画图 @@ -308,7 +308,7 @@ F0IIH/f/QH0wXEQipAoAAAAASUVORK5CYII= In [ ]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -329,7 +329,7 @@ plt.show() In [4]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -780,7 +780,7 @@ zjnnnEsBT7Kcc84551LAkyznnHPOuRTwJMs555xzLgX+B+mOvazOmXQoAAAAAElFTkSuQmCC In [5]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -1202,7 +1202,7 @@ zjnnnEsBT7Kcc84551LAkyznnHPOuRTwJMs555xzLgX+B+mOvazOmXQoAAAAAElFTkSuQmCC In [6]: -``` +```py # 设置图像大小 p = plt.figure(figsize=(10,6), dpi=80) @@ -1646,7 +1646,7 @@ iIiIyCP/A3dzHy2lT8uxAAAAAElFTkSuQmCC In [7]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -2083,7 +2083,7 @@ DprMzMzMCnDQZGZmZlbA/wEMqEO0RIci1gAAAABJRU5ErkJggg== In [8]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -2518,7 +2518,7 @@ JSIiIpKg/wNXpXrhRgRjdwAAAABJRU5ErkJggg== In [9]: -``` +```py # 设置图像大小 f = plt.figure(figsize=(10,6), dpi=80) @@ -2982,7 +2982,7 @@ RETE9RTwiIiIiOsp4BERERHX+xc1HT2p8IKu8QAAAABJRU5ErkJggg== In [10]: -``` +```py # 设置图像大小 plt.figure(figsize=(10,6), dpi=80) @@ -3475,7 +3475,7 @@ HhEREXE8BTwiIiLieAp4RERExPEU8IiIiIjj/Q+2QDD112lDmAAAAABJRU5ErkJggg== In [11]: -``` +```py # 设置图像大小 plt.figure(figsize=(10,6), dpi=80) @@ -4076,7 +4076,7 @@ xpjF+z90lw18wTSaIwAAAABJRU5ErkJggg== In [12]: -``` +```py # 设置图像大小 plt.figure(figsize=(10,6), dpi=80) diff --git a/docs/da/090.md b/docs/da/090.md index f9d72c2bc..dee1f4f83 100644 --- a/docs/da/090.md +++ b/docs/da/090.md @@ -6,7 +6,7 @@ In [1]: -``` +```py %matplotlib inline import numpy as np @@ -300,7 +300,7 @@ YRiGYYTGjIZhGIYRGjMahmEYRmj+P0lg7oy1NXTrAAAAAElFTkSuQmCC In [2]: -``` +```py import numpy as np import matplotlib.mlab as mlab @@ -652,7 +652,7 @@ Lgxre1MOTEUAAAAASUVORK5CYII= In [3]: -``` +```py import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt @@ -910,7 +910,7 @@ RK5CYII= In [4]: -``` +```py import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt @@ -1187,7 +1187,7 @@ MBAp2kIIYSBStIUQwkCkaAshhIFI0RZCCAP5f8NyCaSKvRwCAAAAAElFTkSuQmCC In [5]: -``` +```py from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter @@ -1797,7 +1797,7 @@ RK5CYII= In [6]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -3806,7 +3806,7 @@ IPAAAgggAD9FgMADCCCAAPwU/wetO4AhXrsEhgAAAABJRU5ErkJggg== In [7]: -``` +```py from pylab import figure, show, rand from matplotlib.patches import Ellipse @@ -5003,7 +5003,7 @@ i3wQrLY6AAAAAElFTkSuQmCC In [8]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -5217,7 +5217,7 @@ ueUkZWZmueUkZWZmueUkZWZmueUkZWZmufX/AYMHWp/GzUEOAAAAAElFTkSuQmCC In [9]: -``` +```py import matplotlib.pyplot as plt # The slices will be ordered and plotted counter-clockwise. @@ -5628,7 +5628,7 @@ iL5CDgFqL18+oEPeUSDFmwxdSZKkGJLjeiRJkmJIhq4kSVIMydCVJEmKIRm6kiRJMSRDV5IkKYZk In [10]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -6021,7 +6021,7 @@ nS7kvfVGVvlKci0BB7k351ybL+TenE9LdqZ998NY/X038D5+zIOHnuQHCyGEUOXcK/JsJBX5my/X In [11]: -``` +```py import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook @@ -6606,7 +6606,7 @@ ooQslaQURVGUkKWSlKIoihKyVJJSFEVRQpZKUoqiKErI+v/t1cdmLh3N3wAAAABJRU5ErkJggg== In [12]: -``` +```py import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons @@ -6892,7 +6892,7 @@ BgAAAABJRU5ErkJggg== In [13]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -7119,7 +7119,7 @@ FChb1lWmfwAAAABJRU5ErkJggg== In [14]: -``` +```py """ Show how to make date plots in matplotlib using date tick locators and formatters. See major_minor_demo1.py for more information on @@ -7435,7 +7435,7 @@ OI4TQ1y5O47jxBBX7o7jODHElbvjOE4M+f9EYiNJNukaZgAAAABJRU5ErkJggg== In [15]: -``` +```py import datetime import numpy as np import matplotlib.colors as colors @@ -8662,7 +8662,7 @@ kUjqyf8DRMOAVtE/7MEAAAAASUVORK5CYII= In [16]: -``` +```py import matplotlib.pyplot as plt import numpy as np @@ -15161,7 +15161,7 @@ Qt4G/wW1jjOmOfSF6wAAAABJRU5ErkJggg== In [17]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -15555,7 +15555,7 @@ DkcV4pS/w+FwVCFO+TscDkcV4pS/w+FwVCH/H6Ywvj25v7CVAAAAAElFTkSuQmCC In [18]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -16048,7 +16048,7 @@ yMjICIIsJjIyMoIgi4mMjIwg/H92bEfNtteOcAAAAABJRU5ErkJggg== In [19]: -``` +```py import numpy as np import matplotlib.pyplot as plt @@ -16406,7 +16406,7 @@ JDXAMpekBljmktQAy1ySGvAJpbO10KE3ZZIAAAAASUVORK5CYII= In [20]: -``` +```py from __future__ import print_function import matplotlib.pyplot as plt import os @@ -16531,7 +16531,7 @@ else: ``` -``` +```py 0 $W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$ 1 $\alpha_i > \beta_i,\ \alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ \ldots$ 2 $\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ \left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$ diff --git a/docs/da/093.md b/docs/da/093.md index 78fea297e..1d4ad3c95 100644 --- a/docs/da/093.md +++ b/docs/da/093.md @@ -17,7 +17,7 @@ communication between `py + c` | `import fact` In [1]: -``` +```py %%file fact.h #ifndef FACT_H #define FACT_h @@ -26,14 +26,14 @@ int fact(int n); ``` -``` +```py Writing fact.h ``` In [2]: -``` +```py %%file fact.c #include "fact.h" int fact(int n) @@ -44,7 +44,7 @@ int fact(int n) ``` -``` +```py Writing fact.c ``` @@ -53,7 +53,7 @@ Writing fact.c In [3]: -``` +```py %%file fact_wrap.c /* Must include Python.h before any standard headers*/ @@ -89,7 +89,7 @@ initexample(void) ``` -``` +```py Writing fact_wrap.c ``` @@ -98,7 +98,7 @@ Writing fact_wrap.c 手动使用 `gcc` 编译,`Windows` 下如果没有 `gcc`,可以通过 `conda` 进行安装: -``` +```py conda install mingw4 ``` @@ -106,14 +106,14 @@ conda install mingw4 In [4]: -``` +```py !gcc -DMS_WIN64 -c fact.c fact_wrap.c -IC:\Miniconda\include ``` In [5]: -``` +```py !gcc -DMS_WIN64 -shared fact.o fact_wrap.o -LC:\Miniconda\libs -lpython27 -o example.pyd ``` @@ -124,14 +124,14 @@ In [5]: * `Windows 32-bit` - ``` + ```py gcc -c fact.c fact_wrap.c -I\include gcc -shared fact.o fact_wrap.o -L\libs -lpython27 -o example.pyd ``` * `Unix` - ``` + ```py gcc -c fact.c fact_wrap.c -I gcc -shared fact.o fact_wrap.o -L\config -lpython27 -o example.so ``` @@ -142,13 +142,13 @@ In [5]: In [6]: -``` +```py import example print dir(example) ``` -``` +```py ['__doc__', '__file__', '__name__', '__package__', 'fact'] ``` @@ -157,12 +157,12 @@ print dir(example) In [7]: -``` +```py print 'factorial of 10:', example.fact(10) ``` -``` +```py factorial of 10: 3628800 ``` @@ -173,7 +173,7 @@ factorial of 10: 3628800 In [8]: -``` +```py !rm -f example.pyd ``` @@ -182,7 +182,7 @@ In [8]: In [9]: -``` +```py %%file setup.py from distutils.core import setup, Extension @@ -192,14 +192,14 @@ setup(name='example', ext_modules=[ext]) ``` -``` +```py Writing setup.py ``` 使用 `distutils` 中的函数,我们进行 `build` 和 `install`: -``` +```py python setup.py build (--compiler=mingw64) python setup.py install ``` @@ -210,12 +210,12 @@ python setup.py install In [10]: -``` +```py !python setup.py build_ext --inplace ``` -``` +```py running build_ext building 'example' extension creating build @@ -234,14 +234,14 @@ C:\Miniconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Rele In [11]: -``` +```py import example print 'factorial of 10:', example.fact(10) ``` -``` +```py factorial of 10: 3628800 ``` @@ -250,7 +250,7 @@ factorial of 10: 3628800 In [12]: -``` +```py def pyfact(n): if n <= 1: return 1 return n * pyfact(n-1) @@ -260,7 +260,7 @@ print example.fact(10) ``` -``` +```py 3628800 3628800 @@ -270,12 +270,12 @@ print example.fact(10) In [13]: -``` +```py %timeit example.fact(10) ``` -``` +```py The slowest run took 13.17 times longer than the fastest. This could mean that an intermediate result is being cached 1000000 loops, best of 3: 213 ns per loop @@ -283,12 +283,12 @@ The slowest run took 13.17 times longer than the fastest. This could mean that a In [14]: -``` +```py %timeit pyfact(10) ``` -``` +```py 1000000 loops, best of 3: 1.43 µs per loop ``` @@ -297,14 +297,14 @@ In [14]: In [15]: -``` +```py example.fact(100) ``` Out[15]: -``` +```py 0 ``` @@ -312,14 +312,14 @@ Out[15]: In [16]: -``` +```py pyfact(100) ``` Out[16]: -``` +```py 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L ``` @@ -327,7 +327,7 @@ Out[16]: In [17]: -``` +```py import zipfile f = zipfile.ZipFile('07-02-example.zip','w',zipfile.ZIP_DEFLATED) @@ -344,7 +344,7 @@ f.close() In [18]: -``` +```py !rm -f fact*.* !rm -f example.* !rm -f setup*.* diff --git a/docs/da/094.md b/docs/da/094.md index 86066dd84..5513f662e 100644 --- a/docs/da/094.md +++ b/docs/da/094.md @@ -6,7 +6,7 @@ 考虑之前的斐波拉契数列,`Python` 版本: -``` +```py def fib(n): a,b = 1,1 for i in range(n): @@ -17,7 +17,7 @@ def fib(n): `C` 版本: -``` +```py int fib(int n) { int tmp, i, a, b; a = b = 1; @@ -31,7 +31,7 @@ int fib(int n) { `Cython` 版本: -``` +```py def fib(int n): cdef int i, a, b a,b = 1,1 @@ -60,7 +60,7 @@ def fib(int n): In [1]: -``` +```py %load_ext Cython ``` @@ -69,7 +69,7 @@ In [1]: In [2]: -``` +```py %%cython def cyfib(int n): cdef int i, a, b @@ -82,14 +82,14 @@ def cyfib(int n): In [3]: -``` +```py cyfib(10) ``` Out[3]: -``` +```py 144 ``` @@ -99,7 +99,7 @@ Out[3]: In [4]: -``` +```py %%file fib.pyx def cyfib(int n): cdef int i, a, b @@ -110,14 +110,14 @@ def cyfib(int n): ``` -``` +```py Writing fib.pyx ``` In [5]: -``` +```py %%file setup.py from distutils.core import setup from distutils.extension import Extension @@ -129,7 +129,7 @@ setup(ext_modules=[ext], cmdclass={'build_ext': build_ext}) ``` -``` +```py Overwriting setup.py ``` @@ -138,12 +138,12 @@ Overwriting setup.py In [6]: -``` +```py !python setup.py build_ext --inplace ``` -``` +```py running build_ext cythoning fib.pyx to fib.c building 'fib' extension @@ -160,7 +160,7 @@ C:\Miniconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Rele In [7]: -``` +```py import fib fib.cyfib(10) @@ -169,13 +169,13 @@ fib.cyfib(10) Out[7]: -``` +```py 144 ``` In [8]: -``` +```py import zipfile f = zipfile.ZipFile('07-03-fib.zip','w',zipfile.ZIP_DEFLATED) @@ -194,7 +194,7 @@ f.close() In [9]: -``` +```py !rm -f fib.pyd !rm -f fib.pyc !rm -f fib.C @@ -205,7 +205,7 @@ In [9]: In [10]: -``` +```py %reset -f ``` @@ -214,7 +214,7 @@ In [10]: In [11]: -``` +```py import pyximport pyximport.install() @@ -226,7 +226,7 @@ fib.cyfib(10) Out[11]: -``` +```py 144 ``` @@ -236,7 +236,7 @@ Out[11]: In [12]: -``` +```py !rm -f setup*.* !rm -f fib.* !rm -rf build diff --git a/docs/da/095.md b/docs/da/095.md index f91479c44..f2cb1ead9 100644 --- a/docs/da/095.md +++ b/docs/da/095.md @@ -8,7 +8,7 @@ 可以定义局部变量: -``` +```py def fib(int n): cdef int a,b,i ... @@ -17,7 +17,7 @@ def fib(int n): 定义函数返回值: -``` +```py cdef float distance(float *x, float *y, int n): cdef: int i @@ -30,7 +30,7 @@ cdef float distance(float *x, float *y, int n): 定义函数: -``` +```py cdef class Particle(object): cdef float psn[3], vel[3] cdef int id @@ -51,7 +51,7 @@ cdef class Particle(object): In [1]: -``` +```py from math import sin as pysin from numpy import sin as npsin @@ -59,7 +59,7 @@ from numpy import sin as npsin In [2]: -``` +```py %load_ext Cython ``` @@ -68,7 +68,7 @@ In [2]: In [3]: -``` +```py %%cython from libc.math cimport sin from libc.stdlib cimport malloc, free @@ -81,14 +81,14 @@ from libc.stdlib cimport malloc, free `fib.pxd, fib.pyx` 文件存在,那么可以这样调用: -``` +```py from fib cimport fib ``` 还可以调用 `C++` 标准库和 `Numpy C Api` 中的文件: -``` +```py from libcpp.vector cimport vector cimport numpy as cnp @@ -100,7 +100,7 @@ cimport numpy as cnp In [4]: -``` +```py %%file len_extern.pyx cdef extern from "string.h": int strlen(char *c) @@ -110,7 +110,7 @@ def get_len(char *message): ``` -``` +```py Writing len_extern.pyx ``` @@ -119,7 +119,7 @@ Writing len_extern.pyx In [5]: -``` +```py %%file setup_len_extern.py from distutils.core import setup from distutils.extension import Extension @@ -132,7 +132,7 @@ setup( ``` -``` +```py Writing setup_len_extern.py ``` @@ -141,12 +141,12 @@ Writing setup_len_extern.py In [6]: -``` +```py !python setup_len_extern.py build_ext --inplace ``` -``` +```py running build_ext cythoning len_extern.pyx to len_extern.c building 'len_extern' extension @@ -163,7 +163,7 @@ C:\Miniconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Rele In [7]: -``` +```py import len_extern ``` @@ -172,14 +172,14 @@ import len_extern In [8]: -``` +```py dir(len_extern) ``` Out[8]: -``` +```py ['__builtins__', '__doc__', '__file__', @@ -193,14 +193,14 @@ Out[8]: In [9]: -``` +```py len_extern.get_len('hello') ``` Out[9]: -``` +```py 5 ``` @@ -208,14 +208,14 @@ Out[9]: In [10]: -``` +```py len_extern.get_len('hello\0world!') ``` Out[10]: -``` +```py 5 ``` @@ -223,7 +223,7 @@ Out[10]: In [11]: -``` +```py %%file time_extern.pyx cdef extern from "time.h": @@ -246,7 +246,7 @@ def get_date(): ``` -``` +```py Writing time_extern.pyx ``` @@ -255,7 +255,7 @@ Writing time_extern.pyx In [12]: -``` +```py %%file setup_time_extern.py from distutils.core import setup from distutils.extension import Extension @@ -268,7 +268,7 @@ setup( ``` -``` +```py Writing setup_time_extern.py ``` @@ -277,12 +277,12 @@ Writing setup_time_extern.py In [13]: -``` +```py !python setup_time_extern.py build_ext --inplace ``` -``` +```py running build_ext cythoning time_extern.pyx to time_extern.c building 'time_extern' extension @@ -296,7 +296,7 @@ C:\Miniconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Rele In [14]: -``` +```py import time_extern time_extern.get_date() @@ -305,7 +305,7 @@ time_extern.get_date() Out[14]: -``` +```py (19, 9, 2015) ``` @@ -313,7 +313,7 @@ Out[14]: In [15]: -``` +```py import zipfile f = zipfile.ZipFile('07-04-extern.zip','w',zipfile.ZIP_DEFLATED) diff --git a/docs/da/096.md b/docs/da/096.md index 1a0cfb94a..f6e420f79 100644 --- a/docs/da/096.md +++ b/docs/da/096.md @@ -12,7 +12,7 @@ `Cython` 属性可以使用关键词 `property` 来定义,然后定义 `__get__` 和 `__set__` 方法来进行获取和设置: -``` +```py property name: def __get__(self): return something @@ -29,7 +29,7 @@ property name: In [1]: -``` +```py %%file particle_extern.h #ifndef _PARTICLE_EXTERN_H_ #define _PARTICLE_EXTERN_H_ @@ -65,14 +65,14 @@ class Particle { ``` -``` +```py Overwriting particle_extern.h ``` In [2]: -``` +```py %%file particle_extern.cpp #include "particle_extern.h" @@ -96,7 +96,7 @@ void Particle::applyImpulse(float *f, float t) ``` -``` +```py Overwriting particle_extern.cpp ``` @@ -105,7 +105,7 @@ Overwriting particle_extern.cpp In [3]: -``` +```py %%file particle.pyx import numpy as np @@ -170,14 +170,14 @@ cdef class Particle: ``` -``` +```py Overwriting particle.pyx ``` 首先从头文件声明这个类: -``` +```py cdef extern from "particle_extern.h": cppclass _Particle "Particle": @@ -193,7 +193,7 @@ cdef extern from "particle_extern.h": 这里要使用 `cppclass` 关键词,并且为了方便,我们将 `Particle` 类的名字在 `Cython` 中重命名为 `_Particle`。 -``` +```py cdef class Particle: cdef _Particle *thisptr def __cinit__(self, m, c, float[::1] p, float[::1] v): @@ -207,7 +207,7 @@ cdef class Particle: In [4]: -``` +```py %%file setup.py from distutils.core import setup from distutils.extension import Extension @@ -222,7 +222,7 @@ setup( ``` -``` +```py Overwriting setup.py ``` @@ -231,12 +231,12 @@ Overwriting setup.py In [5]: -``` +```py !python setup.py build_ext -i ``` -``` +```py running build_ext cythoning particle.pyx to particle.cpp building 'particle' extension @@ -247,7 +247,7 @@ C:\Anaconda\Scripts\g++.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Relea ``` -``` +```py particle.cpp: In function 'void __Pyx_RaiseArgtupleInvalid(const char*, int, Py_ssize_t, Py_ssize_t, Py_ssize_t)': particle.cpp:14931:59: warning: unknown conversion type character 'z' in format [-Wformat] particle.cpp:14931:59: warning: format '%s' expects argument of type 'char*', but argument 5 has type 'Py_ssize_t {aka long long int}' [-Wformat] @@ -286,7 +286,7 @@ particle.cpp:16941:50: warning: too many arguments for format [-Wformat-extra-ar In [6]: -``` +```py import particle ``` @@ -295,7 +295,7 @@ import particle In [7]: -``` +```py import numpy as np pos = vel = np.arange(3., dtype='float32') @@ -309,7 +309,7 @@ p Out[7]: -``` +```py particle.Particle(mass=1.0, charge=2.0, pos=[ 0\. 1\. 2.], vel=[ 0\. 1\. 2.]) ``` @@ -317,7 +317,7 @@ particle.Particle(mass=1.0, charge=2.0, pos=[ 0\. 1\. 2.], vel=[ 0\. 1\. 2.] In [8]: -``` +```py p.apply_impulse(np.arange(3., dtype='float32'), 1.0) p @@ -326,7 +326,7 @@ p Out[8]: -``` +```py particle.Particle(mass=1.0, charge=2.0, pos=[ 0\. 1.5 3\. ], vel=[ 0\. 2\. 4.]) ``` @@ -334,14 +334,14 @@ particle.Particle(mass=1.0, charge=2.0, pos=[ 0\. 1.5 3\. ], vel=[ 0\. 2\. In [9]: -``` +```py p.mass ``` Out[9]: -``` +```py 1.0 ``` @@ -349,7 +349,7 @@ Out[9]: In [10]: -``` +```py p.mass = 3.0 ``` @@ -358,14 +358,14 @@ p.mass = 3.0 In [11]: -``` +```py p.charge ``` Out[11]: -``` +```py 2.0 ``` @@ -373,7 +373,7 @@ Out[11]: In [12]: -``` +```py import zipfile f = zipfile.ZipFile('07-05-particle.zip','w',zipfile.ZIP_DEFLATED) diff --git a/docs/da/097.md b/docs/da/097.md index 752410529..b97e62dd1 100644 --- a/docs/da/097.md +++ b/docs/da/097.md @@ -6,7 +6,7 @@ In [1]: -``` +```py %%file cython_sum.pyx def cython_sum(double[::1] a): cdef double s = 0.0 @@ -17,14 +17,14 @@ def cython_sum(double[::1] a): ``` -``` +```py Writing cython_sum.pyx ``` In [2]: -``` +```py %%file setup.py from distutils.core import setup from distutils.extension import Extension @@ -39,19 +39,19 @@ setup( ``` -``` +```py Writing setup.py ``` In [3]: -``` +```py !python setup.py build_ext -i ``` -``` +```py running build_ext cythoning cython_sum.pyx to cython_sum.c building 'cython_sum' extension @@ -64,7 +64,7 @@ C:\Anaconda\Scripts\gcc.bat -DMS_WIN64 -shared -s build\temp.win-amd64-2.7\Relea ``` -``` +```py cython_sum.c: In function '__Pyx_BufFmt_ProcessTypeChunk': cython_sum.c:13561:26: warning: unknown conversion type character 'z' in format [-Wformat] cython_sum.c:13561:26: warning: unknown conversion type character 'z' in format [-Wformat] @@ -103,7 +103,7 @@ cython_sum.c:15253:22: warning: too many arguments for format [-Wformat-extra-ar In [4]: -``` +```py from cython_sum import cython_sum from numpy import * @@ -111,7 +111,7 @@ from numpy import * In [5]: -``` +```py a = arange(1e6) ``` @@ -120,27 +120,27 @@ a = arange(1e6) In [6]: -``` +```py cython_sum(a) ``` Out[6]: -``` +```py 499999500000.0 ``` In [7]: -``` +```py a.sum() ``` Out[7]: -``` +```py 499999500000.0 ``` @@ -148,31 +148,31 @@ Out[7]: In [8]: -``` +```py %timeit cython_sum(a) ``` -``` +```py 100 loops, best of 3: 2.14 ms per loop ``` In [9]: -``` +```py %timeit a.sum() ``` -``` +```py 100 loops, best of 3: 2.38 ms per loop ``` In [10]: -``` +```py import zipfile f = zipfile.ZipFile('07-06-cython-sum.zip','w',zipfile.ZIP_DEFLATED) diff --git a/docs/da/098.md b/docs/da/098.md index cfb38597f..2d88625d5 100644 --- a/docs/da/098.md +++ b/docs/da/098.md @@ -2,7 +2,7 @@ In [1]: -``` +```py %%file fib_orig.pyx def fib(n): a,b = 1,1 @@ -12,14 +12,14 @@ def fib(n): ``` -``` +```py Writing fib_orig.pyx ``` In [2]: -``` +```py !cython -a fib_orig.pyx ``` @@ -28,14 +28,14 @@ In [2]: In [3]: -``` +```py !start fib_orig.html ``` `linux` 下使用: -``` +```py open fib_orig.html ``` diff --git a/docs/da/099.md b/docs/da/099.md index 0bf53ee7b..ba953d2bb 100644 --- a/docs/da/099.md +++ b/docs/da/099.md @@ -6,7 +6,7 @@ In [1]: -``` +```py from ctypes import util, CDLL ``` @@ -17,7 +17,7 @@ from ctypes import util, CDLL In [2]: -``` +```py libc_name = util.find_library('c') # on WINDOWS @@ -25,7 +25,7 @@ print libc_name ``` -``` +```py msvcr90.dll ``` @@ -34,7 +34,7 @@ msvcr90.dll In [3]: -``` +```py libc = CDLL(libc_name) ``` @@ -43,14 +43,14 @@ libc 包含 `C` 标准库中的函数: In [4]: -``` +```py libc.printf ``` Out[4]: -``` +```py <_FuncPtr object at 0x0000000003CEE048> ``` @@ -58,14 +58,14 @@ Out[4]: In [5]: -``` +```py libc.printf("%s, %d\n", "hello", 5) ``` Out[5]: -``` +```py 9 ``` @@ -77,14 +77,14 @@ Out[5]: In [6]: -``` +```py libm_name = util.find_library('m') print libm_name ``` -``` +```py msvcr90.dll ``` @@ -93,14 +93,14 @@ msvcr90.dll In [7]: -``` +```py libm = CDLL(libm_name) libm.atan2(1.0, 2.0) ``` -``` +```py --------------------------------------------------------------------------- ArgumentError Traceback (most recent call last) in () @@ -115,7 +115,7 @@ ArgumentError: argument 1: : Don't know how to conv In [8]: -``` +```py from ctypes import c_double libm.atan2.argtypes = [c_double, c_double] @@ -125,14 +125,14 @@ libm.atan2.restype = c_double In [9]: -``` +```py libm.atan2(1.0, 2.0) ``` Out[9]: -``` +```py 0.4636476090008061 ``` @@ -140,21 +140,21 @@ Out[9]: In [10]: -``` +```py from math import atan2 ``` In [11]: -``` +```py atan2(1.0, 2.0) ``` Out[11]: -``` +```py 0.4636476090008061 ``` @@ -162,7 +162,7 @@ Out[11]: 假设我们有这样的一个函数: -``` +```py float _sum(float *vec, int len) { float sum = 0.0; int i; @@ -176,7 +176,7 @@ float _sum(float *vec, int len) { 并且已经编译成动态链接库,那么我们可以这样调用: -``` +```py from ctypes import c_float, CDLL, c_int from numpy import array, float32 from numpy.ctypeslib import ndpointer diff --git a/docs/da/101.md b/docs/da/101.md index 81398a400..137fe9496 100644 --- a/docs/da/101.md +++ b/docs/da/101.md @@ -6,7 +6,7 @@ In [1]: -``` +```py f = file("new_file", 'w') ``` @@ -15,14 +15,14 @@ f = file("new_file", 'w') In [2]: -``` +```py f.mode ``` Out[2]: -``` +```py 'w' ``` @@ -30,14 +30,14 @@ Out[2]: In [3]: -``` +```py f.closed ``` Out[3]: -``` +```py False ``` @@ -45,12 +45,12 @@ False In [4]: -``` +```py f.mode = 'r' ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -63,12 +63,12 @@ TypeError: readonly attribute In [5]: -``` +```py f.mode() ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -83,7 +83,7 @@ TypeError: 'str' object is not callable In [6]: -``` +```py f.write('Hi.\n') f.seek(0) f.write('Hola!\n') @@ -93,7 +93,7 @@ f.close() In [7]: -``` +```py !rm new_file ``` diff --git a/docs/da/102.md b/docs/da/102.md index 474618e26..c80a7b507 100644 --- a/docs/da/102.md +++ b/docs/da/102.md @@ -2,7 +2,7 @@ In [1]: -``` +```py %matplotlib inline import matplotlib.pyplot as plt @@ -14,7 +14,7 @@ import numpy as np In [2]: -``` +```py class Forest(object): def __init__(self, size=(150, 150), p_sapling=0.0025, p_lightning=5.e-6, name=None): self.size = size @@ -73,7 +73,7 @@ class Forest(object): In [3]: -``` +```py forest = Forest() ``` @@ -82,12 +82,12 @@ forest = Forest() In [4]: -``` +```py print forest.trees ``` -``` +```py [[False False False ..., False False False] [False False False ..., False False False] [False False False ..., False False False] @@ -100,12 +100,12 @@ print forest.trees In [5]: -``` +```py print forest.forest_fires ``` -``` +```py [[False False False ..., False False False] [False False False ..., False False False] [False False False ..., False False False] @@ -120,7 +120,7 @@ print forest.forest_fires In [6]: -``` +```py plt.matshow(forest.trees, cmap=plt.cm.Greens) plt.show() @@ -195,7 +195,7 @@ QmCC In [7]: -``` +```py forest.advance_one_step() plt.matshow(forest.trees, cmap=plt.cm.Greens) plt.show() @@ -275,7 +275,7 @@ H+OqGfP4E0uBAAAAAElFTkSuQmCC In [8]: -``` +```py for i in range(500): forest.advance_one_step() plt.matshow(forest.trees, cmap=plt.cm.Greens) @@ -283,7 +283,7 @@ print forest.tree_fraction ``` -``` +```py 0.253111111111 ``` @@ -487,7 +487,7 @@ umuSMqXPktIjabewndc6Unqk/XkzHIHD4dgYFrGz0OFwLA/OETgcDp8IHA6HTwQOhwM+ETgcDvhE In [9]: -``` +```py forest = Forest() tree_fractions = [] for i in range(5000): diff --git a/docs/da/103.md b/docs/da/103.md index 369e1a056..6113c4b65 100644 --- a/docs/da/103.md +++ b/docs/da/103.md @@ -6,34 +6,34 @@ In [1]: -``` +```py a = 257 ``` In [2]: -``` +```py type(a) ``` Out[2]: -``` +```py int ``` In [3]: -``` +```py id(a) ``` Out[3]: -``` +```py 53187032L ``` @@ -41,27 +41,27 @@ Out[3]: In [4]: -``` +```py b = a ``` In [5]: -``` +```py id(b) ``` Out[5]: -``` +```py 53187032L ``` In [6]: -``` +```py c = 258 id(c) @@ -69,7 +69,7 @@ id(c) Out[6]: -``` +```py 53186960L ``` @@ -77,7 +77,7 @@ Out[6]: In [7]: -``` +```py def foo(): print 'hi' @@ -85,27 +85,27 @@ def foo(): In [8]: -``` +```py type(foo) ``` Out[8]: -``` +```py function ``` In [9]: -``` +```py id(foo) ``` Out[9]: -``` +```py 63632664L ``` @@ -113,27 +113,27 @@ Out[9]: In [10]: -``` +```py type(type) ``` Out[10]: -``` +```py type ``` In [11]: -``` +```py id(type) ``` Out[11]: -``` +```py 506070640L ``` @@ -141,12 +141,12 @@ Out[11]: In [12]: -``` +```py id(if) ``` -``` +```py File "", line 1 id(if) ^ @@ -156,12 +156,12 @@ SyntaxError: invalid syntax In [13]: -``` +```py id(+) ``` -``` +```py File "", line 1 id(+) ^ diff --git a/docs/da/104.md b/docs/da/104.md index 1494267a3..a7e9c946f 100644 --- a/docs/da/104.md +++ b/docs/da/104.md @@ -4,7 +4,7 @@ `class` 定义如下: -``` +```py class ClassName(ParentClass): """class docstring""" def method(self): @@ -22,7 +22,7 @@ class ClassName(ParentClass): In [1]: -``` +```py class Forest(object): """ Forest can grow trees which eventually die.""" pass @@ -35,13 +35,13 @@ class Forest(object): In [2]: -``` +```py import numpy as np np.info(Forest) ``` -``` +```py Forest() Forest can grow trees which eventually die. @@ -52,21 +52,21 @@ Methods: In [3]: -``` +```py forest = Forest() ``` In [4]: -``` +```py forest ``` Out[4]: -``` +```py <__main__.Forest at 0x3cda358> ``` @@ -76,21 +76,21 @@ Out[4]: In [5]: -``` +```py forest.trees = np.zeros((150, 150), dtype=bool) ``` In [6]: -``` +```py forest.trees ``` Out[6]: -``` +```py array([[False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], @@ -102,7 +102,7 @@ array([[False, False, False, ..., False, False, False], In [7]: -``` +```py forest2 = Forest() ``` @@ -111,12 +111,12 @@ forest2 = Forest() In [8]: -``` +```py forest2.trees ``` -``` +```py --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () @@ -129,7 +129,7 @@ AttributeError: 'Forest' object has no attribute 'trees' In [9]: -``` +```py class Forest(object): """ Forest can grow trees which eventually die.""" def grow(self): @@ -145,7 +145,7 @@ class Forest(object): In [10]: -``` +```py forest = Forest() forest.grow() @@ -153,7 +153,7 @@ forest.number(12) ``` -``` +```py the tree is growing! there are 12 trees. diff --git a/docs/da/105.md b/docs/da/105.md index a867ac980..5dce74370 100644 --- a/docs/da/105.md +++ b/docs/da/105.md @@ -20,7 +20,7 @@ In [1]: -``` +```py class Leaf(object): """ A leaf falling in the woods. @@ -34,14 +34,14 @@ class Leaf(object): In [2]: -``` +```py leaf1 = Leaf() print leaf1.color ``` -``` +```py green ``` @@ -50,14 +50,14 @@ green In [3]: -``` +```py leaf2 = Leaf('orange') print leaf2.color ``` -``` +```py orange ``` @@ -66,7 +66,7 @@ orange In [4]: -``` +```py import numpy as np class Forest(object): @@ -81,7 +81,7 @@ class Forest(object): In [5]: -``` +```py forest = Forest() forest.trees @@ -90,7 +90,7 @@ forest.trees Out[5]: -``` +```py array([[False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], @@ -102,14 +102,14 @@ array([[False, False, False, ..., False, False, False], In [6]: -``` +```py forest.fires ``` Out[6]: -``` +```py array([[False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], @@ -123,7 +123,7 @@ array([[False, False, False, ..., False, False, False], In [7]: -``` +```py forest.trees[0,0]=True forest.trees @@ -131,7 +131,7 @@ forest.trees Out[7]: -``` +```py array([[ True, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], @@ -145,7 +145,7 @@ array([[ True, False, False, ..., False, False, False], In [8]: -``` +```py forest2 = Forest() forest2.trees @@ -154,7 +154,7 @@ forest2.trees Out[8]: -``` +```py array([[False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], @@ -166,14 +166,14 @@ array([[False, False, False, ..., False, False, False], 事实上,`__new__()` 才是真正产生新对象的方法,`__init__()` 只是对对象进行了初始化,所以: -``` +```py leaf = Leaf() ``` 相当于 -``` +```py my_new_leaf = Leaf.__new__(Leaf) Leaf.__init__(my_new_leaf) leaf = my_new_leaf @@ -184,7 +184,7 @@ leaf = my_new_leaf In [9]: -``` +```py class Leaf(object): """ A leaf falling in the woods. @@ -204,14 +204,14 @@ class Leaf(object): In [10]: -``` +```py leaf = Leaf() print leaf ``` -``` +```py A green leaf ``` @@ -220,14 +220,14 @@ A green leaf In [11]: -``` +```py leaf ``` Out[11]: -``` +```py Leaf(color='green') ``` @@ -235,7 +235,7 @@ Leaf(color='green') In [12]: -``` +```py import numpy as np class Forest(object): @@ -256,7 +256,7 @@ class Forest(object): In [13]: -``` +```py forest = Forest() ``` @@ -265,12 +265,12 @@ forest = Forest() In [14]: -``` +```py print forest ``` -``` +```py Forest ``` @@ -279,14 +279,14 @@ Forest In [15]: -``` +```py forest ``` Out[15]: -``` +```py Forest(size=(150, 150)) ``` @@ -294,26 +294,26 @@ Forest(size=(150, 150)) In [16]: -``` +```py forest.__class__ ``` Out[16]: -``` +```py __main__.Forest ``` In [17]: -``` +```py forest.__class__.__name__ ``` Out[17]: -``` +```py 'Forest' ``` \ No newline at end of file diff --git a/docs/da/106.md b/docs/da/106.md index 30fa65b93..4e367b7d0 100644 --- a/docs/da/106.md +++ b/docs/da/106.md @@ -6,7 +6,7 @@ In [1]: -``` +```py class Leaf(object): def __init__(self, mass_mg): self.mass_mg = mass_mg @@ -22,14 +22,14 @@ class Leaf(object): In [2]: -``` +```py leaf = Leaf(200) print leaf.mass_oz ``` -``` +```py 0.00706 ``` @@ -38,14 +38,14 @@ print leaf.mass_oz In [3]: -``` +```py leaf.mass_mg = 150 print leaf.mass_oz ``` -``` +```py 0.005295 ``` @@ -54,12 +54,12 @@ print leaf.mass_oz In [4]: -``` +```py leaf.mass_oz() ``` -``` +```py --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () @@ -72,12 +72,12 @@ TypeError: 'float' object is not callable In [5]: -``` +```py leaf.mass_oz = 0.001 ``` -``` +```py --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () @@ -90,7 +90,7 @@ AttributeError: can't set attribute In [6]: -``` +```py import numpy as np class Forest(object): @@ -134,7 +134,7 @@ class Forest(object): In [7]: -``` +```py forest = Forest() forest.num_cells @@ -143,7 +143,7 @@ forest.num_cells Out[7]: -``` +```py 22500 ``` @@ -151,7 +151,7 @@ Out[7]: In [8]: -``` +```py small_forest = Forest((10, 10)) small_forest.num_cells @@ -159,7 +159,7 @@ small_forest.num_cells Out[8]: -``` +```py 100 ``` @@ -167,27 +167,27 @@ Out[8]: In [9]: -``` +```py small_forest.tree_fraction ``` Out[9]: -``` +```py 0.0 ``` In [10]: -``` +```py small_forest.fire_fraction ``` Out[10]: -``` +```py 0.0 ``` @@ -197,7 +197,7 @@ Out[10]: In [11]: -``` +```py class Leaf(object): def __init__(self, mass_mg): self.mass_mg = mass_mg @@ -218,7 +218,7 @@ class Leaf(object): In [12]: -``` +```py leaf = Leaf(200) print leaf.mass_oz @@ -227,7 +227,7 @@ print leaf.mass_oz ``` -``` +```py 0.00706 0.005295 @@ -237,20 +237,20 @@ print leaf.mass_oz In [13]: -``` +```py leaf.mass_oz = 0.01 print leaf.mass_mg ``` -``` +```py 283.28611898 ``` 一个等价的替代如下: -``` +```py class Leaf(object): def __init__(self, mass_mg): self.mass_mg = mass_mg diff --git a/docs/da/107.md b/docs/da/107.md index 206d025fb..6c555ebd4 100644 --- a/docs/da/107.md +++ b/docs/da/107.md @@ -13,7 +13,7 @@ In [1]: -``` +```py import numpy as np class Forest(object): @@ -72,7 +72,7 @@ class Forest(object): In [2]: -``` +```py forest = Forest() print forest.tree_fraction @@ -81,7 +81,7 @@ print forest.tree_fraction ``` -``` +```py 0.0 0.00293333333333 @@ -99,7 +99,7 @@ print forest.tree_fraction In [3]: -``` +```py import numpy as np class Forest(object): @@ -186,7 +186,7 @@ class Forest(object): In [4]: -``` +```py forest = Forest() for i in range(100): @@ -198,7 +198,7 @@ for i in range(100): In [5]: -``` +```py import matplotlib.pyplot as plt from matplotlib import cm @@ -404,7 +404,7 @@ Az4ROBwO+ETgcDgA/H9fWFGYjphtAwAAAABJRU5ErkJggg== In [6]: -``` +```py forest = Forest() forest2 = Forest(p_lightning=5e-4) diff --git a/docs/da/108.md b/docs/da/108.md index e81837103..eac62b398 100644 --- a/docs/da/108.md +++ b/docs/da/108.md @@ -2,7 +2,7 @@ 一个类定义的基本形式如下: -``` +```py class ClassName(ParentClass): """class docstring""" def method(self): @@ -24,7 +24,7 @@ class ClassName(ParentClass): In [1]: -``` +```py class Leaf(object): def __init__(self, color="green"): self.color = color @@ -37,26 +37,26 @@ class Leaf(object): In [2]: -``` +```py leaf = Leaf() print leaf.color ``` -``` +```py green ``` In [3]: -``` +```py leaf.fall() ``` -``` +```py Splat! ``` @@ -65,7 +65,7 @@ Splat! In [4]: -``` +```py class MapleLeaf(Leaf): def change_color(self): if self.color == "green": @@ -77,26 +77,26 @@ class MapleLeaf(Leaf): In [5]: -``` +```py mleaf = MapleLeaf() print mleaf.color ``` -``` +```py green ``` In [6]: -``` +```py mleaf.fall() ``` -``` +```py Splat! ``` @@ -105,14 +105,14 @@ Splat! In [7]: -``` +```py mleaf.change_color() print mleaf.color ``` -``` +```py red ``` @@ -121,7 +121,7 @@ red In [8]: -``` +```py class MapleLeaf(Leaf): def change_color(self): if self.color == "green": @@ -134,7 +134,7 @@ class MapleLeaf(Leaf): In [9]: -``` +```py mleaf = MapleLeaf() print mleaf.color @@ -143,7 +143,7 @@ print mleaf.color ``` -``` +```py green Plunk! red diff --git a/docs/da/109.md b/docs/da/109.md index c73aa272d..09b2efb66 100644 --- a/docs/da/109.md +++ b/docs/da/109.md @@ -1,6 +1,6 @@ # super() 函数 -``` +```py super(CurrentClassName, instance) ``` @@ -8,7 +8,7 @@ super(CurrentClassName, instance) In [1]: -``` +```py class Leaf(object): def __init__(self, color="green"): self.color = color @@ -29,7 +29,7 @@ class MapleLeaf(Leaf): In [2]: -``` +```py mleaf = MapleLeaf() print mleaf.color @@ -38,7 +38,7 @@ print mleaf.color ``` -``` +```py green Splat! red @@ -49,7 +49,7 @@ red In [3]: -``` +```py import numpy as np class Forest(object): @@ -106,7 +106,7 @@ class Forest(object): In [4]: -``` +```py class BurnableForest(Forest): """ Burnable forest support fires @@ -160,7 +160,7 @@ class BurnableForest(Forest): In [5]: -``` +```py forest = Forest() forest.grow_trees() @@ -169,7 +169,7 @@ print forest.tree_fraction ``` -``` +```py 0.00284444444444 ``` @@ -178,7 +178,7 @@ print forest.tree_fraction In [6]: -``` +```py burnable_forest = BurnableForest() ``` @@ -187,7 +187,7 @@ burnable_forest = BurnableForest() In [7]: -``` +```py burnable_forest.grow_trees() burnable_forest.start_fires() burnable_forest.burn_trees() @@ -195,7 +195,7 @@ print burnable_forest.tree_fraction ``` -``` +```py 0.00235555555556 ``` @@ -204,7 +204,7 @@ print burnable_forest.tree_fraction In [8]: -``` +```py import matplotlib.pyplot as plt %matplotlib inline @@ -511,50 +511,50 @@ QloBSvaEENIKULInhJBWgJI9IYS0ApTsCSGkFaBkTwghrcD/B0LrH2UND7W5AAAAAElFTkSuQmCC In [9]: -``` +```py forest ``` Out[9]: -``` +```py Forest(size=(150, 150)) ``` In [10]: -``` +```py forest2 ``` Out[10]: -``` +```py BurnableForest(size=(150, 150)) ``` In [11]: -``` +```py print forest ``` -``` +```py Forest ``` In [12]: -``` +```py print forest2 ``` -``` +```py BurnableForest ``` \ No newline at end of file diff --git a/docs/da/110.md b/docs/da/110.md index 9d0180002..8bc58b34b 100644 --- a/docs/da/110.md +++ b/docs/da/110.md @@ -9,7 +9,7 @@ In [1]: -``` +```py import numpy as np from scipy.ndimage.measurements import label @@ -130,7 +130,7 @@ class InstantBurnForest(BurnableForest): In [2]: -``` +```py forest = Forest() sb_forest = SlowBurnForest() ib_forest = InstantBurnForest() @@ -150,7 +150,7 @@ for i in xrange(1500): In [3]: -``` +```py import matplotlib.pyplot as plt %matplotlib inline diff --git a/docs/da/111.md b/docs/da/111.md index 266e2eb27..bc53e4fb9 100644 --- a/docs/da/111.md +++ b/docs/da/111.md @@ -12,7 +12,7 @@ In [1]: -``` +```py class Leaf(object): def __init__(self, color="green"): self.color = color @@ -25,7 +25,7 @@ class Leaf(object): In [2]: -``` +```py class MapleLeaf(Leaf): def fall(self): self.color = 'brown' @@ -37,7 +37,7 @@ class MapleLeaf(Leaf): In [3]: -``` +```py class Acorn(object): def fall(self): print "Plunk!" @@ -48,7 +48,7 @@ class Acorn(object): In [4]: -``` +```py objects = [Leaf(), MapleLeaf(), Acorn()] for obj in objects: @@ -56,7 +56,7 @@ for obj in objects: ``` -``` +```py Splat! Splat! Plunk! @@ -69,7 +69,7 @@ Plunk! In [5]: -``` +```py import numpy as np from scipy.ndimage.measurements import label @@ -198,7 +198,7 @@ class InstantBurnForest(BurnableForest): In [6]: -``` +```py forest = Forest() b_forest = BurnableForest() sb_forest = SlowBurnForest() @@ -219,7 +219,7 @@ for i in xrange(1500): In [7]: -``` +```py import matplotlib.pyplot as plt %matplotlib inline diff --git a/docs/da/112.md b/docs/da/112.md index 6790e6c06..676ddef77 100644 --- a/docs/da/112.md +++ b/docs/da/112.md @@ -7,7 +7,7 @@ In [1]: -``` +```py class MyClass(object): def __init__(self): print "I'm special!" @@ -22,36 +22,36 @@ class MyClass(object): In [2]: -``` +```py m = MyClass() ``` -``` +```py I'm special! ``` In [3]: -``` +```py m.public() ``` -``` +```py I'm public! ``` In [4]: -``` +```py m._private() ``` -``` +```py I'm private! ``` @@ -60,12 +60,12 @@ I'm private! In [5]: -``` +```py m._MyClass__really_special() ``` -``` +```py I'm really special! ``` \ No newline at end of file diff --git a/docs/da/113.md b/docs/da/113.md index adbefd5a7..da2ce0af1 100644 --- a/docs/da/113.md +++ b/docs/da/113.md @@ -4,7 +4,7 @@ In [1]: -``` +```py class Leaf(object): def __init__(self, color='green'): self.color = color @@ -26,7 +26,7 @@ class MapleLeaf(ColorChangingLeaf, DeciduousLeaf): In [2]: -``` +```py leaf = MapleLeaf() leaf.change("yellow") @@ -36,7 +36,7 @@ leaf.fall() ``` -``` +```py yellow Plunk! @@ -46,7 +46,7 @@ Plunk! In [3]: -``` +```py class Leaf(object): def __init__(self, color='green'): self.color = color @@ -68,20 +68,20 @@ class MapleLeaf(ColorChangingLeaf, DeciduousLeaf): In [4]: -``` +```py leaf = MapleLeaf() leaf.fall() ``` -``` +```py Spalt! ``` In [5]: -``` +```py class MapleLeaf(DeciduousLeaf, ColorChangingLeaf): pass @@ -89,13 +89,13 @@ class MapleLeaf(DeciduousLeaf, ColorChangingLeaf): In [6]: -``` +```py leaf = MapleLeaf() leaf.fall() ``` -``` +```py Plunk! ``` @@ -104,14 +104,14 @@ Plunk! In [7]: -``` +```py MapleLeaf.__mro__ ``` Out[7]: -``` +```py (__main__.MapleLeaf, __main__.DeciduousLeaf, __main__.ColorChangingLeaf, @@ -121,14 +121,14 @@ Out[7]: In [8]: -``` +```py MapleLeaf.mro() ``` Out[8]: -``` +```py [__main__.MapleLeaf, __main__.DeciduousLeaf, __main__.ColorChangingLeaf, @@ -140,7 +140,7 @@ Out[8]: In [9]: -``` +```py class A(object): pass @@ -165,13 +165,13 @@ class D(B1, C): In [10]: -``` +```py D.mro() ``` Out[10]: -``` +```py [__main__.D, __main__.B1, __main__.B, __main__.C, __main__.A, object] ``` \ No newline at end of file diff --git a/docs/da/115.md b/docs/da/115.md index 4931d597d..e48e0df86 100644 --- a/docs/da/115.md +++ b/docs/da/115.md @@ -18,14 +18,14 @@ `windows` 下,使用 `anaconda` 安装 `theano` 的命令为: -``` +```py conda install mingw libpython pip install theano ``` `linux` 下,使用 `anaconda` 安装的命令为 -``` +```py conda install theano ``` @@ -35,7 +35,7 @@ conda install theano In [1]: -``` +```py import theano theano.__version__ @@ -44,7 +44,7 @@ theano.__version__ Out[1]: -``` +```py '0.7.0.dev-54186290a97186b9c6b76317e007844529a352f4' ``` @@ -52,14 +52,14 @@ Out[1]: In [2]: -``` +```py theano.config.device ``` Out[2]: -``` +```py 'cpu' ``` @@ -67,18 +67,18 @@ Out[2]: In [3]: -``` +```py theano.test() ``` -``` +```py /usr/local/lib/python2.7/dist-packages/theano/misc/pycuda_init.py:34: UserWarning: PyCUDA import failed in theano.misc.pycuda_init warnings.warn("PyCUDA import failed in theano.misc.pycuda_init") ....................S............... ``` -``` +```py Theano version 0.7.0.dev-54186290a97186b9c6b76317e007844529a352f4 theano is installed in /usr/local/lib/python2.7/dist-packages/theano NumPy version 1.10.1 @@ -89,7 +89,7 @@ nose version 1.3.7 ``` -``` +```py ---------------------------------------------------------------------- Ran 37 tests in 37.919s @@ -99,7 +99,7 @@ OK (SKIP=1) Out[3]: -``` +```py ``` diff --git a/docs/da/116.md b/docs/da/116.md index b2cabd4bf..b93676409 100644 --- a/docs/da/116.md +++ b/docs/da/116.md @@ -2,7 +2,7 @@ In [1]: -``` +```py %matplotlib inline import numpy as np import matplotlib.pyplot as plt @@ -13,7 +13,7 @@ import matplotlib.pyplot as plt In [2]: -``` +```py import theano # 一般都把 `tensor` 子模块导入并命名为 T @@ -21,7 +21,7 @@ import theano.tensor as T ``` -``` +```py Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) ``` @@ -36,19 +36,19 @@ Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) In [3]: -``` +```py foo = T.scalar('x') ``` In [4]: -``` +```py print foo ``` -``` +```py x ``` @@ -57,14 +57,14 @@ x In [5]: -``` +```py bar = foo ** 2 print bar ``` -``` +```py Elemwise{pow,no_inplace}.0 ``` @@ -75,12 +75,12 @@ Elemwise{pow,no_inplace}.0 In [6]: -``` +```py print theano.pp(bar) ``` -``` +```py (x ** TensorConstant{2}) ``` @@ -89,13 +89,13 @@ print theano.pp(bar) In [7]: -``` +```py print type(foo) print foo.type ``` -``` +```py TensorType(float32, scalar) @@ -105,7 +105,7 @@ TensorType(float32, scalar) 有了符号变量,自然可以用符号变量来定义函数,`theano.function()` 函数用来生成符号函数: -``` +```py theano.function(input, output) ``` @@ -115,7 +115,7 @@ theano.function(input, output) In [8]: -``` +```py square = theano.function([foo], bar) ``` @@ -124,12 +124,12 @@ square = theano.function([foo], bar) In [9]: -``` +```py print square(3) ``` -``` +```py 9.0 ``` @@ -138,12 +138,12 @@ print square(3) In [10]: -``` +```py print bar.eval({foo: 3}) ``` -``` +```py 9.0 ``` @@ -184,14 +184,14 @@ print bar.eval({foo: 3}) 除此之外,还可以用它们的复数形式一次定义多个符号变量: -``` +```py x,y,z = T.vectors('x','y','z') x,y,z = T.vectors(3) ``` In [11]: -``` +```py A = T.matrix('A') x = T.vector('x') b = T.vector('b') @@ -202,7 +202,7 @@ b = T.vector('b') In [12]: -``` +```py y = T.dot(A, x) + b ``` @@ -211,7 +211,7 @@ y = T.dot(A, x) + b In [13]: -``` +```py z = T.sum(A**2) ``` @@ -220,7 +220,7 @@ z = T.sum(A**2) In [14]: -``` +```py linear_mix = theano.function([A, x, b], [y, z]) @@ -230,7 +230,7 @@ linear_mix = theano.function([A, x, b], $$ A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix}, x = \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix}, b = \begin{bmatrix} 4 \\ 5 \end{bmatrix} $$In [15]: -``` +```py print linear_mix(np.array([[1, 2, 3], [4, 5, 6]], dtype=theano.config.floatX), #A np.array([1, 2, 3], dtype=theano.config.floatX), #x @@ -238,7 +238,7 @@ print linear_mix(np.array([[1, 2, 3], ``` -``` +```py [array([ 18., 37.], dtype=float32), array(91.0, dtype=float32)] ``` @@ -249,7 +249,7 @@ print linear_mix(np.array([[1, 2, 3], In [16]: -``` +```py linear_mix_default = theano.function([A, x, theano.Param(b, default=np.zeros(2, dtype=theano.config.floatX))], [y, z]) @@ -259,14 +259,14 @@ linear_mix_default = theano.function([A, x, theano.Param(b, default=np.zeros(2, In [17]: -``` +```py print linear_mix_default(np.array([[1, 2, 3], [4, 5, 6]], dtype=theano.config.floatX), #A np.array([1, 2, 3], dtype=theano.config.floatX)) #x ``` -``` +```py [array([ 14., 32.], dtype=float32), array(91.0, dtype=float32)] ``` @@ -275,7 +275,7 @@ print linear_mix_default(np.array([[1, 2, 3], In [18]: -``` +```py print linear_mix_default(np.array([[1, 2, 3], [4, 5, 6]], dtype=theano.config.floatX), #A np.array([1, 2, 3], dtype=theano.config.floatX), #x @@ -283,7 +283,7 @@ print linear_mix_default(np.array([[1, 2, 3], ``` -``` +```py [array([ 18., 37.], dtype=float32), array(91.0, dtype=float32)] ``` @@ -294,14 +294,14 @@ print linear_mix_default(np.array([[1, 2, 3], In [19]: -``` +```py shared_var = theano.shared(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=theano.config.floatX)) print shared_var.type ``` -``` +```py CudaNdarrayType(float32, matrix) ``` @@ -310,7 +310,7 @@ CudaNdarrayType(float32, matrix) In [20]: -``` +```py shared_var.set_value(np.array([[3.0, 4], [2, 1]], dtype=theano.config.floatX)) ``` @@ -319,12 +319,12 @@ shared_var.set_value(np.array([[3.0, 4], [2, 1]], dtype=theano.config.floatX)) In [21]: -``` +```py print shared_var.get_value() ``` -``` +```py [[ 3\. 4.] [ 2\. 1.]] @@ -334,7 +334,7 @@ print shared_var.get_value() In [22]: -``` +```py shared_square = shared_var ** 2 f = theano.function([], shared_square) @@ -343,7 +343,7 @@ print f() ``` -``` +```py [[ 9\. 16.] [ 4\. 1.]] @@ -355,14 +355,14 @@ print f() In [23]: -``` +```py shared_var.set_value(np.array([[1.0, 2], [3, 4]], dtype=theano.config.floatX)) print f() ``` -``` +```py [[ 1\. 4.] [ 9\. 16.]] @@ -372,7 +372,7 @@ print f() In [24]: -``` +```py subtract = T.matrix('subtract') f_update = theano.function([subtract], shared_var, updates={shared_var: shared_var - subtract}) @@ -383,7 +383,7 @@ f_update = theano.function([subtract], shared_var, updates={shared_var: shared_v In [25]: -``` +```py print 'before update:' print shared_var.get_value() @@ -395,7 +395,7 @@ print shared_var.get_value() ``` -``` +```py before update: [[ 1\. 2.] [ 3\. 4.]] @@ -415,14 +415,14 @@ after update: In [26]: -``` +```py bar_grad = T.grad(bar, foo) # 表示 bar (x^2) 关于 foo (x) 的导数 print bar_grad.eval({foo: 10}) ``` -``` +```py 20.0 ``` @@ -431,7 +431,7 @@ print bar_grad.eval({foo: 10}) In [27]: -``` +```py y_J = theano.gradient.jacobian(y, x) print y_J.eval({A: np.array([[9.0, 8, 7], [4, 5, 6]], dtype=theano.config.floatX), #A @@ -440,7 +440,7 @@ print y_J.eval({A: np.array([[9.0, 8, 7], [4, 5, 6]], dtype=theano.config.floatX ``` -``` +```py [[ 9\. 8\. 7.] [ 4\. 5\. 6.]] @@ -456,7 +456,7 @@ Rop 用来计算 $\frac{\partial f}{\partial x}v$,Lop 用来计算 $v\frac{\pa In [28]: -``` +```py W = T.dmatrix('W') V = T.dmatrix('V') x = T.dvector('x') @@ -468,7 +468,7 @@ print f([[1, 1], [1, 1]], [[2, 2], [2, 2]], [0,1]) ``` -``` +```py [ 2\. 2.] ``` \ No newline at end of file diff --git a/docs/da/117.md b/docs/da/117.md index 8b787da8d..97a9dbe08 100644 --- a/docs/da/117.md +++ b/docs/da/117.md @@ -10,7 +10,7 @@ 首先是用 `anaconda` 安装 `theano`: -``` +```py conda install mingw libpython pip install theano ``` @@ -55,39 +55,39 @@ Cuda 的版本与电脑的显卡兼容。 In [1]: -``` +```py %%file test_theano.py from theano import config print 'using device:', config.device ``` -``` +```py Writing test_theano.py ``` 我们可以通过临时设置环境变量 `THEANO_FLAGS` 来改变 `theano` 的运行模式,在 linux 下,临时环境变量直接用: -``` +```py THEANO_FLAGS=xxx ``` 就可以完成,设置完成之后,该环境变量只在当前的命令窗口有效,你可以这样运行你的代码: -``` +```py THEANO_FLAGS=xxx python .py ``` 在 `Windows` 下,需要使用 `set` 命令来临时设置环境变量,所以运行方式为: -``` +```py set THEANO_FLAGS=xxx && python .py ``` In [2]: -``` +```py import sys if sys.platform == 'win32': @@ -97,14 +97,14 @@ else: ``` -``` +```py using device: cpu ``` In [3]: -``` +```py if sys.platform == 'win32': !set THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 && python test_theano.py else: @@ -112,7 +112,7 @@ else: ``` -``` +```py Using gpu device 0: Tesla C2075 (CNMeM is disabled) using device: gpu @@ -122,7 +122,7 @@ using device: gpu In [4]: -``` +```py %%file test_theano.py from theano import function, config, shared, sandbox @@ -150,14 +150,14 @@ else: ``` -``` +```py Overwriting test_theano.py ``` In [5]: -``` +```py if sys.platform == 'win32': !set THEANO_FLAGS=mode=FAST_RUN,device=cpu,floatX=float32 && python test_theano.py else: @@ -165,7 +165,7 @@ else: ``` -``` +```py Looping 1000 times took 3.498123 seconds Result is [ 1.23178029 1.61879337 1.52278066 ..., 2.20771813 2.29967761 1.62323284] @@ -175,7 +175,7 @@ Used the cpu In [6]: -``` +```py if sys.platform == 'win32': !set THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 && python test_theano.py else: @@ -183,7 +183,7 @@ else: ``` -``` +```py Using gpu device 0: Tesla C2075 (CNMeM is disabled) Looping 1000 times took 0.847006 seconds Result is [ 1.23178029 1.61879349 1.52278066 ..., 2.20771813 2.29967761 @@ -198,7 +198,7 @@ Used the gpu In [7]: -``` +```py %%file test_theano.py from theano import function, config, shared, sandbox @@ -228,14 +228,14 @@ else: ``` -``` +```py Overwriting test_theano.py ``` In [8]: -``` +```py if sys.platform == 'win32': !set THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 && python test_theano.py else: @@ -243,7 +243,7 @@ else: ``` -``` +```py Using gpu device 0: Tesla C2075 (CNMeM is disabled) Looping 1000 times took 0.318359 seconds Result is @@ -255,7 +255,7 @@ Used the gpu In [9]: -``` +```py !rm test_theano.py ``` @@ -266,7 +266,7 @@ In [9]: 例如我现在的 .theanorc.txt 配置为: -``` +```py [global] device = gpu floatX = float32 diff --git a/docs/da/118.md b/docs/da/118.md index edebab7e6..67c806bca 100644 --- a/docs/da/118.md +++ b/docs/da/118.md @@ -12,7 +12,7 @@ In [1]: -``` +```py import theano import theano.tensor as T @@ -22,7 +22,7 @@ z = x + y ``` -``` +```py Using gpu device 0: GeForce GTX 850M ``` @@ -42,24 +42,24 @@ Using gpu device 0: GeForce GTX 850M 安装完之后,找到 `pydot.py` 将其中: -``` +```py graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) ) ``` 修改为: -``` +```py graph.append( '%s %s {\n' % (self.obj_dict['type'], quote_if_necessary(self.obj_dict['name'])) ) ``` In [2]: -``` +```py theano.printing.pydotprint(z, outfile='apply1.png', var_with_name_simple=True) ``` -``` +```py The output file is available at apply1.png ``` @@ -72,14 +72,14 @@ The output file is available at apply1.png In [3]: -``` +```py z.owner.op.name ``` Out[3]: -``` +```py 'Elemwise{add,no_inplace}' ``` @@ -87,13 +87,13 @@ Out[3]: In [4]: -``` +```py print z.owner.nin print z.owner.nout ``` -``` +```py 2 1 @@ -103,14 +103,14 @@ print z.owner.nout In [5]: -``` +```py z.owner.inputs ``` Out[5]: -``` +```py [x, y] ``` @@ -118,12 +118,12 @@ Out[5]: In [6]: -``` +```py print theano.printing.pprint(z) ``` -``` +```py (x + y) ``` @@ -132,12 +132,12 @@ print theano.printing.pprint(z) In [7]: -``` +```py theano.printing.debugprint(z) ``` -``` +```py Elemwise{add,no_inplace} [@A] '' |x [@B] |y [@C] @@ -148,7 +148,7 @@ Elemwise{add,no_inplace} [@A] '' In [8]: -``` +```py y = x * 2 ``` @@ -157,12 +157,12 @@ y = x * 2 In [9]: -``` +```py theano.printing.debugprint(y) ``` -``` +```py Elemwise{mul,no_inplace} [@A] '' |x [@B] |DimShuffle{x,x} [@C] '' @@ -174,14 +174,14 @@ Elemwise{mul,no_inplace} [@A] '' In [10]: -``` +```py y.owner.inputs[1].owner.op ``` Out[10]: -``` +```py ``` @@ -189,25 +189,25 @@ Out[10]: In [11]: -``` +```py y.owner.inputs[1].owner.inputs ``` Out[11]: -``` +```py [TensorConstant{2}] ``` In [12]: -``` +```py theano.printing.pydotprint(y, outfile='apply2.png', var_with_name_simple=True) ``` -``` +```py The output file is available at apply2.png ``` @@ -218,7 +218,7 @@ The output file is available at apply2.png In [13]: -``` +```py a = T.dscalar('a') b = a + a ** 10 @@ -228,13 +228,13 @@ f = theano.function([a], b) In [14]: -``` +```py theano.printing.pydotprint(b, outfile='apply_no_opti.png', var_with_name_simple=True) theano.printing.pydotprint(f, outfile='apply_opti.png', var_with_name_simple=True) ``` -``` +```py The output file is available at apply_no_opti.png The output file is available at apply_opti.png diff --git a/docs/da/119.md b/docs/da/119.md index f4d8344b3..7c2a4341d 100644 --- a/docs/da/119.md +++ b/docs/da/119.md @@ -6,7 +6,7 @@ In [1]: -``` +```py import theano import theano.tensor as T @@ -14,7 +14,7 @@ print theano.config ``` -``` +```py floatX (('float64', 'float32', 'float16')) Doc: Default floating-point precision for python casts. @@ -562,7 +562,7 @@ lib.cnmem () ``` -``` +```py Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) ``` @@ -583,13 +583,13 @@ Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) 使用 `THEANO_FLAGS` 环境变量,运行程序的方法如下: -``` +```py THEANO_FLAGS='floatX=float32,device=gpu0,nvcc.fastmath=True' python .py ``` 如果是 `window` 下,则需要进行稍微的改动: -``` +```py set THEANO_FLAGS='floatX=float32,device=gpu0,nvcc.fastmath=True' && python .py ``` @@ -601,7 +601,7 @@ set THEANO_FLAGS='floatX=float32,device=gpu0,nvcc.fastmath=True' && python in () diff --git a/docs/da/120.md b/docs/da/120.md index 94cf381d7..cc17d1a46 100644 --- a/docs/da/120.md +++ b/docs/da/120.md @@ -12,7 +12,7 @@ In [1]: -``` +```py import theano, time import theano.tensor as T import numpy as np @@ -20,7 +20,7 @@ from theano.ifelse import ifelse ``` -``` +```py Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) ``` @@ -33,7 +33,7 @@ $$ \mathbf z = f(a, b,\mathbf{x, y}) = \left\{ \begin{aligned} \mathbf x & ,\ a In [2]: -``` +```py a, b = T.scalars('a', 'b') x, y = T.matrices('x', 'y') @@ -43,7 +43,7 @@ x, y = T.matrices('x', 'y') In [3]: -``` +```py z_ifelse = ifelse(T.lt(a, b), x, y) f_ifelse = theano.function([a, b, x, y], z_ifelse) @@ -54,7 +54,7 @@ f_ifelse = theano.function([a, b, x, y], z_ifelse) In [4]: -``` +```py z_switch = T.switch(T.lt(a, b), x, y) f_switch = theano.function([a, b, x, y], z_switch) @@ -65,7 +65,7 @@ f_switch = theano.function([a, b, x, y], z_switch) In [5]: -``` +```py val1 = 0. val2 = 1. big_mat1 = np.ones((10000, 1000), dtype=theano.config.floatX) @@ -77,7 +77,7 @@ big_mat2 = np.ones((10000, 1000), dtype=theano.config.floatX) In [6]: -``` +```py n_times = 10 tic = time.clock() @@ -92,7 +92,7 @@ print 'time spent evaluating one value %f sec' % (time.clock() - tic) ``` -``` +```py time spent evaluating both values 0.638598 sec time spent evaluating one value 0.461249 sec diff --git a/docs/da/121.md b/docs/da/121.md index cdbafc8ce..828942166 100644 --- a/docs/da/121.md +++ b/docs/da/121.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import theano, time import theano.tensor as T import numpy as np @@ -12,7 +12,7 @@ def floatX(X): ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -35,7 +35,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) 函数的用法如下: -``` +```py theano.scan(fn, sequences=None, outputs_info=None, @@ -76,14 +76,14 @@ theano.scan(fn, 这里实现一个简单的 `map` 操作,将向量 $\mathbf x$ 中的所有元素变成原来的两倍: -``` +```py map(lambda t: t * 2, x) ``` In [2]: -``` +```py x = T.vector() results, _ = theano.scan(fn = lambda t: t * 2, @@ -94,7 +94,7 @@ print x_double_scan(range(10)) ``` -``` +```py [ 0\. 2\. 4\. 6\. 8\. 10\. 12\. 14\. 16\. 18.] ``` @@ -107,7 +107,7 @@ print x_double_scan(range(10)) In [3]: -``` +```py result, _ = theano.map(fn = lambda t: t * 2, sequences = x) x_double_map = theano.function([x], result) @@ -116,7 +116,7 @@ print x_double_map(range(10)) ``` -``` +```py [ 0\. 2\. 4\. 6\. 8\. 10\. 12\. 14\. 16\. 18.] ``` @@ -125,14 +125,14 @@ print x_double_map(range(10)) 这里一个简单的 `reduce` 操作,求和: -``` +```py reduce(lambda a, b: a + b, x) ``` In [4]: -``` +```py result, _ = theano.scan(fn = lambda t, v: t + v, sequences = x, outputs_info = floatX(0.)) @@ -145,7 +145,7 @@ print x_sum_scan(range(10)) ``` -``` +```py 45.0 ``` @@ -154,7 +154,7 @@ print x_sum_scan(range(10)) In [5]: -``` +```py result, _ = theano.reduce(fn = lambda t, v: t + v, sequences = x, outputs_info = 0.) @@ -166,7 +166,7 @@ print x_sum_reduce(range(10)) ``` -``` +```py 45.0 ``` @@ -198,7 +198,7 @@ print x_sum_reduce(range(10)) 第二部分则是更新规则的字典,告诉我们如何对 `scan` 中使用到的一些共享的变量进行更新: -``` +```py return [y1_t, y2_t], {x:x+1} ``` @@ -211,7 +211,7 @@ return [y1_t, y2_t], {x:x+1} 例如,在我们的第一个例子中 -``` +```py theano.scan(fn = lambda t: t * 2, sequences = x) @@ -221,7 +221,7 @@ theano.scan(fn = lambda t: t * 2, 再如,在我们的第二个例子中: -``` +```py theano.scan(fn = lambda t, v: t + v, sequences = x, outputs_info = floatX(0.)) @@ -236,7 +236,7 @@ theano.scan(fn = lambda t, v: t + v, In [6]: -``` +```py # 变量 x x = T.scalar("x") @@ -262,7 +262,7 @@ print polynomial(floatX(10), ``` -``` +```py 2301.0 ``` @@ -280,7 +280,7 @@ print polynomial(floatX(10), 传入 `fn` 的参数也会按照 `taps` 中的顺序来排列,我们考虑下面这个例子: -``` +```py scan(fn, sequences = [ dict(input= Sequence1, taps = [-3,2,-1]) , Sequence2 , dict(input = Sequence3, taps = 3) ] @@ -293,7 +293,7 @@ scan(fn, sequences = [ dict(input= Sequence1, taps = [-3,2,-1]) 首先是 `Sequence1` 的 `[-3, 2, -1]` 被传入,然后 `Sequence2` 不是 `dict`, 所以传入默认值 `[0]`,`Sequence3` 传入的参数是 `3`,所以 `fn` 在第 `t` 步接受的前几个参数是: -``` +```py Sequence1[t-3] Sequence1[t+2] Sequence1[t-1] @@ -303,7 +303,7 @@ Sequence3[t+3] 然后 `Output1` 传入的是 `[-3, -5]`(**传入的初始值的形状应为 `shape (5,)+`**),`Output2` 不作为参数传入,`Output3` 传入的是 `[-1]`,所以接下的参数是: -``` +```py Output1[t-3] Output1[t-5] Output3[t-1] @@ -313,7 +313,7 @@ Argument2 总的说来上面的例子中,`fn` 函数按照以下顺序最多接受这样 10 个参数: -``` +```py Sequence1[t-3] Sequence1[t+2] Sequence1[t-1] @@ -330,7 +330,7 @@ Argument2 In [7]: -``` +```py X = T.matrix("X") Y = T.vector("y") @@ -353,7 +353,7 @@ Y_seq = theano.function(inputs = [X, Y, W_1, W_2, W_3], In [8]: -``` +```py # 测试 t = 1001 x_dim = 10 @@ -386,7 +386,7 @@ print "the max difference of the first 10 results is", np.max(np.abs(y_res_thean ``` -``` +```py theano running time 0.0537 s numpy running time 0.0197 s the max difference of the first 10 results is 1.25780650354e-06 @@ -397,7 +397,7 @@ the max difference of the first 10 results is 1.25780650354e-06 In [9]: -``` +```py # 测试 t = 1001 x_dim = 100 @@ -430,7 +430,7 @@ print "the max difference of the first 10 results is", np.max(np.abs(y_res_thean ``` -``` +```py theano running time 0.0754 s numpy running time 0.1334 s the max difference of the first 10 results is 0.000656997077348 @@ -441,14 +441,14 @@ the max difference of the first 10 results is 0.000656997077348 In [10]: -``` +```py for i in xrange(20): print "iter {:03d}, max diff:{:.6f}".format(i + 1, np.max(np.abs(y_res_numpy[i + 1,:] - y_res_theano[i,:]))) ``` -``` +```py iter 001, max diff:0.000002 iter 002, max diff:0.000005 iter 003, max diff:0.000007 @@ -478,7 +478,7 @@ iter 020, max diff:0.123678 In [11]: -``` +```py A = T.matrix("A") k = T.iscalar("k") @@ -504,7 +504,7 @@ print a_k ``` -``` +```py [[ 107616\. -152192.] [ -76096\. 107616.]] [[ 107616\. -152192.] @@ -518,7 +518,7 @@ print a_k In [12]: -``` +```py n = theano.shared(floatX(0)) k = T.iscalar("k") @@ -539,7 +539,7 @@ print n.get_value() ``` -``` +```py 0.0 10.0 20.0 @@ -558,7 +558,7 @@ print n.get_value() In [13]: -``` +```py max_value = T.scalar() results, _ = theano.scan(fn = lambda v_pre, max_v: (v_pre * 2, theano.scan_module.until(v_pre * 2 > max_v)), @@ -575,7 +575,7 @@ print power_of_2(40) ``` -``` +```py [ 2\. 4\. 8\. 16\. 32.] ``` \ No newline at end of file diff --git a/docs/da/122.md b/docs/da/122.md index f6a3cf397..3b7f6fe94 100644 --- a/docs/da/122.md +++ b/docs/da/122.md @@ -12,7 +12,7 @@ In [1]: -``` +```py %matplotlib inline from matplotlib import pyplot as plt import numpy as np @@ -21,7 +21,7 @@ from theano import tensor as T ``` -``` +```py Using gpu device 0: GeForce GTX 850M ``` @@ -32,7 +32,7 @@ Using gpu device 0: GeForce GTX 850M In [2]: -``` +```py a = T.scalar() b = T.scalar() @@ -44,7 +44,7 @@ y = a * b In [3]: -``` +```py multiply = theano.function(inputs=[a, b], outputs=y) ``` @@ -53,13 +53,13 @@ multiply = theano.function(inputs=[a, b], outputs=y) In [4]: -``` +```py print multiply(3, 2) # 6 print multiply(4, 5) # 20 ``` -``` +```py 6.0 20.0 @@ -71,7 +71,7 @@ print multiply(4, 5) # 20 In [5]: -``` +```py train_X = np.linspace(-1, 1, 101) train_Y = 2 * train_X + 1 + np.random.randn(train_X.size) * 0.33 @@ -81,7 +81,7 @@ train_Y = 2 * train_X + 1 + np.random.randn(train_X.size) * 0.33 In [6]: -``` +```py plt.scatter(train_X, train_Y) plt.show() @@ -209,7 +209,7 @@ RU5ErkJggg== In [7]: -``` +```py X = T.scalar() Y = T.scalar() @@ -219,7 +219,7 @@ Y = T.scalar() In [8]: -``` +```py X.name = 'x' Y.name = 'y' @@ -229,7 +229,7 @@ Y.name = 'y' In [9]: -``` +```py def model(X, w, b): return X * w + b @@ -241,7 +241,7 @@ def model(X, w, b): In [10]: -``` +```py w = theano.shared(np.asarray(0., dtype=theano.config.floatX)) w.name = 'w' b = theano.shared(np.asarray(0., dtype=theano.config.floatX)) @@ -253,7 +253,7 @@ b.name = 'b' In [11]: -``` +```py Y_bar = model(X, w, b) theano.pp(Y_bar) @@ -262,7 +262,7 @@ theano.pp(Y_bar) Out[11]: -``` +```py '((x * HostFromGpu(w)) + HostFromGpu(b))' ``` @@ -270,7 +270,7 @@ Out[11]: In [12]: -``` +```py cost = T.mean(T.sqr(Y_bar - Y)) grads = T.grad(cost=cost, wrt=[w, b]) @@ -280,7 +280,7 @@ grads = T.grad(cost=cost, wrt=[w, b]) In [13]: -``` +```py lr = 0.01 updates = [[w, w - grads[0] * lr], [b, b - grads[1] * lr]] @@ -293,7 +293,7 @@ updates = [[w, w - grads[0] * lr], In [14]: -``` +```py train_model = theano.function(inputs=[X,Y], outputs=cost, updates=updates, @@ -307,7 +307,7 @@ train_model = theano.function(inputs=[X,Y], In [15]: -``` +```py for i in xrange(100): for x, y in zip(train_X, train_Y): train_model(x, y) @@ -318,7 +318,7 @@ for i in xrange(100): In [16]: -``` +```py print w.get_value() # 接近 2 print b.get_value() # 接近 1 @@ -329,7 +329,7 @@ plt.show() ``` -``` +```py 1.94257426262 1.00938093662 diff --git a/docs/da/123.md b/docs/da/123.md index 2fc696538..962c69bf2 100644 --- a/docs/da/123.md +++ b/docs/da/123.md @@ -2,7 +2,7 @@ In [1]: -``` +```py %matplotlib inline import numpy as np import matplotlib.pyplot as plt @@ -11,7 +11,7 @@ import theano.tensor as T ``` -``` +```py Using gpu device 0: GeForce GTX 850M ``` @@ -24,7 +24,7 @@ Using gpu device 0: GeForce GTX 850M In [2]: -``` +```py x = T.matrix('x') s = 1 / (1 + T.exp(-x)) sigmoid = theano.function([x], s, allow_input_downcast=True) @@ -35,7 +35,7 @@ sigmoid = theano.function([x], s, allow_input_downcast=True) In [3]: -``` +```py sigmoid([[ 0, 1], [-1,-2]]) @@ -43,7 +43,7 @@ sigmoid([[ 0, 1], Out[3]: -``` +```py array([[ 0.5 , 0.7310586 ], [ 0.26894143, 0.11920293]], dtype=float32) ``` @@ -52,7 +52,7 @@ array([[ 0.5 , 0.7310586 ], In [4]: -``` +```py X = np.linspace(-6, 6, 100) X = X[np.newaxis,:] @@ -325,7 +325,7 @@ tZIkSUo9i1pJkiSl3v8H7tR/QglpVT0AAAAASUVORK5CYII= In [5]: -``` +```py s2 = (1 + T.tanh(x / 2)) / 2 sigmoid2 = theano.function([x], s2) @@ -337,7 +337,7 @@ sigmoid2([[ 0, 1], Out[5]: -``` +```py array([[ 0.5 , 0.7310586 ], [ 0.26894143, 0.11920291]], dtype=float32) ``` @@ -366,7 +366,7 @@ $$- y \log(h_{w,b}(x)) - (1-y) \log(1-h_{w,b}(x))$$ In [6]: -``` +```py rng = np.random # 数据大小和规模 @@ -382,7 +382,7 @@ D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2)) In [7]: -``` +```py x = T.matrix('x') y = T.vector('y') @@ -396,7 +396,7 @@ b = theano.shared(0., name='b') In [8]: -``` +```py h = 1 / (1 + T.exp(-T.dot(x, w) - b)) ``` @@ -405,7 +405,7 @@ h = 1 / (1 + T.exp(-T.dot(x, w) - b)) In [9]: -``` +```py prediction = h > 0.5 ``` @@ -414,7 +414,7 @@ prediction = h > 0.5 In [10]: -``` +```py cost = - T.mean(y * T.log(h) + (1 - y) * T.log(1 - h)) + 0.01 * T.sum(w ** 2) # 正则项,防止过拟合 gw, gb = T.grad(cost, [w, b]) @@ -424,7 +424,7 @@ gw, gb = T.grad(cost, [w, b]) In [11]: -``` +```py train = theano.function(inputs=[x, y], outputs=cost, updates=[[w, w - 0.1 * gw], [b, b - 0.1 * gb]], @@ -438,7 +438,7 @@ predict = theano.function(inputs=[x], In [12]: -``` +```py for i in xrange(10001): err = train(D[0], D[1]) if i % 1000 == 0: @@ -446,7 +446,7 @@ for i in xrange(10001): ``` -``` +```py iter 0, error 19.295896 iter 1000, error 0.210341 iter 2000, error 0.126124 @@ -465,12 +465,12 @@ iter 10000, error 0.124845 In [13]: -``` +```py print D[1] ``` -``` +```py [0 0 0 1 1 0 1 1 1 0 0 1 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 0 1 1 0 0 0 0 1 0 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 1 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 1 0 1 0 0 0 1 0 1 1 1 0 1 1 0 1 0 0 1 0 0 1 0 1 1 1 1 0 1 0 @@ -487,12 +487,12 @@ print D[1] In [14]: -``` +```py print predict(D[0]) ``` -``` +```py [0 0 0 1 1 0 1 1 1 0 0 1 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 0 0 1 1 0 0 0 0 1 0 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 1 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 1 1 0 1 0 0 0 1 0 1 1 1 0 1 1 0 1 0 0 1 0 0 1 0 1 1 1 1 0 1 0 diff --git a/docs/da/124.md b/docs/da/124.md index c8ff3fe79..9758aa0ed 100644 --- a/docs/da/124.md +++ b/docs/da/124.md @@ -8,7 +8,7 @@ In [1]: -``` +```py %%file download_mnist.py import os import os.path @@ -33,7 +33,7 @@ download_and_gzip('mnist/t10k-labels-idx1-ubyte') ``` -``` +```py Overwriting download_mnist.py ``` @@ -42,7 +42,7 @@ Overwriting download_mnist.py In [2]: -``` +```py %run download_mnist.py ``` @@ -53,7 +53,7 @@ In [2]: In [3]: -``` +```py %%file load.py import numpy as np import os @@ -106,7 +106,7 @@ def mnist(ntrain=60000,ntest=10000,onehot=True): ``` -``` +```py Overwriting load.py ``` @@ -123,7 +123,7 @@ Overwriting load.py In [4]: -``` +```py import theano from theano import tensor as T import numpy as np @@ -131,7 +131,7 @@ from load import mnist ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -142,7 +142,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [5]: -``` +```py def floatX(X): return np.asarray(X, dtype=theano.config.floatX) @@ -155,7 +155,7 @@ def init_weights(shape): In [6]: -``` +```py A = T.matrix() B = T.nnet.softmax(A) @@ -173,7 +173,7 @@ print b.sum(1) ``` -``` +```py (3, 4) [ 1.00000012 1\. 1\. ] @@ -185,7 +185,7 @@ print b.sum(1) In [7]: -``` +```py def model(X, w): return T.nnet.softmax(T.dot(X, w)) @@ -195,7 +195,7 @@ def model(X, w): In [8]: -``` +```py trX, teX, trY, teY = mnist(onehot=True) ``` @@ -204,7 +204,7 @@ trX, teX, trY, teY = mnist(onehot=True) In [9]: -``` +```py X = T.fmatrix() Y = T.fmatrix() @@ -216,7 +216,7 @@ w = init_weights((784, 10)) In [10]: -``` +```py py_x = model(X, w) y_pred = T.argmax(py_x, axis=1) @@ -226,7 +226,7 @@ y_pred = T.argmax(py_x, axis=1) In [11]: -``` +```py cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) gradient = T.grad(cost=cost, wrt=w) update = [[w, w - gradient * 0.05]] @@ -237,7 +237,7 @@ update = [[w, w - gradient * 0.05]] In [12]: -``` +```py train = theano.function(inputs=[X, Y], outputs=cost, updates=update, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs=y_pred, allow_input_downcast=True) @@ -247,7 +247,7 @@ predict = theano.function(inputs=[X], outputs=y_pred, allow_input_downcast=True) In [13]: -``` +```py for i in range(100): for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): cost = train(trX[start:end], trY[start:end]) @@ -255,7 +255,7 @@ for i in range(100): ``` -``` +```py 000 0.8862 001 0.8985 002 0.9042 diff --git a/docs/da/125.md b/docs/da/125.md index b0d92a4ff..610959198 100644 --- a/docs/da/125.md +++ b/docs/da/125.md @@ -6,7 +6,7 @@ In [1]: -``` +```py import theano import theano.tensor as T @@ -15,7 +15,7 @@ from load import mnist ``` -``` +```py Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) ``` @@ -26,7 +26,7 @@ Using gpu device 1: Tesla K10.G2.8GB (CNMeM is disabled) $$ \begin{aligned} h & = \sigma (W_h X) \\ o & = \text{softmax} (W_o h) \end{aligned} $$In [2]: -``` +```py def model(X, w_h, w_o): """ input: @@ -48,7 +48,7 @@ def model(X, w_h, w_o): In [3]: -``` +```py def sgd(cost, params, lr=0.05): """ input: @@ -72,7 +72,7 @@ def sgd(cost, params, lr=0.05): In [4]: -``` +```py def floatX(X): return np.asarray(X, dtype=theano.config.floatX) @@ -85,7 +85,7 @@ def init_weights(shape): In [5]: -``` +```py X = T.matrix() Y = T.matrix() @@ -98,7 +98,7 @@ w_o = init_weights((625, 10)) In [6]: -``` +```py py_x = model(X, w_h, w_o) ``` @@ -107,7 +107,7 @@ py_x = model(X, w_h, w_o) In [7]: -``` +```py y_x = T.argmax(py_x, axis=1) ``` @@ -116,7 +116,7 @@ y_x = T.argmax(py_x, axis=1) In [8]: -``` +```py cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) ``` @@ -125,7 +125,7 @@ cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) In [9]: -``` +```py updates = sgd(cost, [w_h, w_o]) ``` @@ -134,7 +134,7 @@ updates = sgd(cost, [w_h, w_o]) In [10]: -``` +```py train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) @@ -146,7 +146,7 @@ predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) In [11]: -``` +```py trX, teX, trY, teY = mnist(onehot=True) ``` @@ -155,7 +155,7 @@ trX, teX, trY, teY = mnist(onehot=True) In [12]: -``` +```py for i in range(100): for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)): cost = train(trX[start:end], trY[start:end]) @@ -163,7 +163,7 @@ for i in range(100): ``` -``` +```py 000 0.7028 001 0.8285 002 0.8673 diff --git a/docs/da/126.md b/docs/da/126.md index c7fc68ec8..6108fb9a1 100644 --- a/docs/da/126.md +++ b/docs/da/126.md @@ -2,14 +2,14 @@ In [1]: -``` +```py import theano import theano.tensor as T import numpy as np ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -18,7 +18,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py from theano.sandbox.rng_mrg import MRG_RandomStreams ``` @@ -27,7 +27,7 @@ from theano.sandbox.rng_mrg import MRG_RandomStreams In [3]: -``` +```py srng = MRG_RandomStreams() ``` @@ -47,7 +47,7 @@ srng = MRG_RandomStreams() In [4]: -``` +```py rand_size = T.vector(dtype="int64") rand_normal = srng.normal(rand_size.shape) @@ -63,7 +63,7 @@ print f_rand(range(5))[2] ``` -``` +```py [ 0.10108768 -1.64354193 0.71042836 -0.77760422 0.06291872] [ 0.23193923 0.71880513 0.03122572 0.97318739 0.99260223] [0 1 0 1 1] diff --git a/docs/da/127.md b/docs/da/127.md index b3559cde5..243075be0 100644 --- a/docs/da/127.md +++ b/docs/da/127.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import theano import theano.tensor as T import numpy as np @@ -16,7 +16,7 @@ def floatX(X): ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -27,7 +27,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py def dropout(X, prob=0.): if prob > 0: X *= srng.binomial(X.shape, p=1-prob, dtype = theano.config.floatX) @@ -50,7 +50,7 @@ $$ \begin{aligned} & h_1 = \text{rectify}(W_{h_1} \ x) \\ & h_2 = \text{rectify} In [3]: -``` +```py def softmax(X): e_x = T.exp(X - X.max(axis=1).dimshuffle(0, 'x')) return e_x / e_x.sum(axis=1).dimshuffle(0, 'x') @@ -85,7 +85,7 @@ def model(X, w_h1, w_h2, w_o, p_drop_input, p_drop_hidden): In [4]: -``` +```py def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.01)) @@ -99,7 +99,7 @@ w_o = init_weights((625, 10)) In [5]: -``` +```py X = T.matrix() Y = T.matrix() @@ -109,7 +109,7 @@ Y = T.matrix() In [6]: -``` +```py def RMSprop(cost, params, accs, lr=0.001, rho=0.9, epsilon=1e-6): grads = T.grad(cost=cost, wrt=params) updates = [] @@ -127,7 +127,7 @@ def RMSprop(cost, params, accs, lr=0.001, rho=0.9, epsilon=1e-6): In [7]: -``` +```py # 有 dropout,用来训练 noise_h1, noise_h2, noise_py_x = model(X, w_h1, w_h2, w_o, 0.2, 0.5) cost = T.mean(T.nnet.categorical_crossentropy(noise_py_x, Y)) @@ -143,7 +143,7 @@ train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_inpu In [8]: -``` +```py # 没有 dropout,用来预测 h1, h2, py_x = model(X, w_h1, w_h2, w_o, 0., 0.) # 预测的结果 @@ -156,7 +156,7 @@ predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) In [9]: -``` +```py trX, teX, trY, teY = mnist(onehot=True) for i in range(50): @@ -166,7 +166,7 @@ for i in range(50): ``` -``` +```py iter 001 accuracy: 0.943 iter 002 accuracy: 0.9665 iter 003 accuracy: 0.9732 diff --git a/docs/da/128.md b/docs/da/128.md index 6699373cb..2aaeb7da2 100644 --- a/docs/da/128.md +++ b/docs/da/128.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams @@ -13,7 +13,7 @@ srng = RandomStreams() ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -22,7 +22,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py def floatX(X): return np.asarray(X, dtype=theano.config.floatX) @@ -61,7 +61,7 @@ def RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6): In [3]: -``` +```py from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d @@ -81,7 +81,7 @@ from theano.tensor.signal.downsample import max_pool_2d In [4]: -``` +```py trX, teX, trY, teY = mnist(onehot=True) trX = trX.reshape(-1, 1, 28, 28) @@ -95,7 +95,7 @@ teX = teX.reshape(-1, 1, 28, 28) In [5]: -``` +```py def model(X, w, w2, w3, w4, p_drop_conv, p_drop_hidden): # X: 128 * 1 * 28 * 28 @@ -149,7 +149,7 @@ def model(X, w, w2, w3, w4, p_drop_conv, p_drop_hidden): In [6]: -``` +```py X = T.ftensor4() Y = T.fmatrix() @@ -165,7 +165,7 @@ w_o = init_weights((625, 10)) In [7]: -``` +```py noise_l1, noise_l2, noise_l3, noise_l4, noise_py_x = model(X, w, w2, w3, w4, 0.2, 0.5) ``` @@ -174,7 +174,7 @@ noise_l1, noise_l2, noise_l3, noise_l4, noise_py_x = model(X, w, w2, w3, w4, 0.2 In [8]: -``` +```py l1, l2, l3, l4, py_x = model(X, w, w2, w3, w4, 0., 0.) y_x = T.argmax(py_x, axis=1) @@ -184,7 +184,7 @@ y_x = T.argmax(py_x, axis=1) In [9]: -``` +```py cost = T.mean(T.nnet.categorical_crossentropy(noise_py_x, Y)) params = [w, w2, w3, w4, w_o] updates = RMSprop(cost, params, lr=0.001) @@ -195,7 +195,7 @@ updates = RMSprop(cost, params, lr=0.001) In [10]: -``` +```py train = theano.function(inputs=[X, Y], outputs=cost, updates=updates, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs=y_x, allow_input_downcast=True) @@ -206,7 +206,7 @@ for i in range(50): ``` -``` +```py iter 001, 0.917 iter 002, 0.974 iter 003, 0.983 diff --git a/docs/da/129.md b/docs/da/129.md index fe1ff0b43..ac4385be2 100644 --- a/docs/da/129.md +++ b/docs/da/129.md @@ -6,13 +6,13 @@ In [1]: -``` +```py import theano import theano.tensor as T ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -23,7 +23,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py x = T.fmatrix() print type(x) @@ -31,7 +31,7 @@ print type(T.fmatrix) ``` -``` +```py @@ -43,7 +43,7 @@ print type(T.fmatrix) In [3]: -``` +```py x = T.scalar('myvar', dtype='int32') x = T.iscalar('myvar') x = T.TensorType(dtype='int32', broadcastable=())('myvar') @@ -93,7 +93,7 @@ x = T.TensorType(dtype='int32', broadcastable=())('myvar') In [4]: -``` +```py dtensor5 = T.TensorType('float64', (False,)*5) x = dtensor5() @@ -108,12 +108,12 @@ x = dtensor5() In [5]: -``` +```py print x.ndim ``` -``` +```py 5 ``` @@ -124,12 +124,12 @@ print x.ndim In [6]: -``` +```py print x.type ``` -``` +```py TensorType(float64, 5D) ``` @@ -140,12 +140,12 @@ TensorType(float64, 5D) In [7]: -``` +```py print x.dtype ``` -``` +```py float64 ``` @@ -156,7 +156,7 @@ float64 In [8]: -``` +```py shape = T.ivector("shape") y = x.reshape(shape, ndim=3) @@ -167,12 +167,12 @@ y = x.reshape(shape, ndim=3) In [9]: -``` +```py print x.ndim, y.ndim ``` -``` +```py 5 3 ``` @@ -197,7 +197,7 @@ print x.ndim, y.ndim In [10]: -``` +```py z = y.dimshuffle(("x", 1, 2, 0)) print z @@ -205,7 +205,7 @@ print z.ndim ``` -``` +```py DimShuffle{x,1,2,0}.0 4 @@ -217,14 +217,14 @@ DimShuffle{x,1,2,0}.0 In [11]: -``` +```py z = x.flatten(ndim=2) print z.ndim ``` -``` +```py 2 ``` @@ -241,12 +241,12 @@ print z.ndim In [12]: -``` +```py print filter(lambda t: t.isalpha(), dir(x)) ``` -``` +```py ['T', 'all', 'any', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh', 'argmax', 'argmin', 'argsort', 'astype', 'broadcastable', 'ceil', 'choose', 'clip', 'clone', 'compress', 'conj', 'conjugate', 'copy', 'cos', 'cosh', 'cumprod', 'cumsum', 'diagonal', 'dimshuffle', 'dot', 'dtype', 'eval', 'exp', 'fill', 'flatten', 'floor', 'imag', 'index', 'log', 'max', 'mean', 'min', 'name', 'ndim', 'nonzero', 'norm', 'owner', 'prod', 'ptp', 'ravel', 'real', 'repeat', 'reshape', 'round', 'shape', 'sin', 'sinh', 'size', 'sort', 'sqrt', 'squeeze', 'std', 'sum', 'swapaxes', 'tag', 'take', 'tan', 'tanh', 'trace', 'transpose', 'trunc', 'type', 'var'] ``` @@ -261,12 +261,12 @@ print filter(lambda t: t.isalpha(), dir(x)) In [13]: -``` +```py print T.shape(x) ``` -``` +```py Shape.0 ``` @@ -277,7 +277,7 @@ Shape.0 In [14]: -``` +```py x = T.tensor3() print T.shape_padleft(x) @@ -285,7 +285,7 @@ print T.shape_padright(x) ``` -``` +```py DimShuffle{x,0,1,2}.0 DimShuffle{0,1,2,x}.0 @@ -297,14 +297,14 @@ DimShuffle{0,1,2,x}.0 In [15]: -``` +```py print T.shape_padaxis(x, 1) print T.shape_padaxis(x, 0) print T.shape_padaxis(x, -1) ``` -``` +```py DimShuffle{0,x,1,2}.0 DimShuffle{x,0,1,2}.0 DimShuffle{0,1,2,x}.0 diff --git a/docs/da/130.md b/docs/da/130.md index b40184d2b..24bd4b613 100644 --- a/docs/da/130.md +++ b/docs/da/130.md @@ -2,14 +2,14 @@ In [1]: -``` +```py import theano import theano.tensor as T import numpy as np ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -20,14 +20,14 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py t = T.arange(9) print t[1::2].eval() ``` -``` +```py [1 3 5 7] ``` @@ -36,14 +36,14 @@ print t[1::2].eval() In [3]: -``` +```py n = np.arange(9) print n[1::2] ``` -``` +```py [1 3 5 7] ``` @@ -54,14 +54,14 @@ print n[1::2] In [4]: -``` +```py t = T.arange(9).reshape((3,3)) print t[t > 4].eval() ``` -``` +```py [[[0 1 2] [0 1 2] [0 1 2]] @@ -80,14 +80,14 @@ print t[t > 4].eval() In [5]: -``` +```py n = np.arange(9).reshape((3,3)) print n[n > 4] ``` -``` +```py [5 6 7 8] ``` @@ -96,12 +96,12 @@ print n[n > 4] In [6]: -``` +```py print t[(t > 4).nonzero()].eval() ``` -``` +```py [5 6 7 8] ``` @@ -118,7 +118,7 @@ print t[(t > 4).nonzero()].eval() In [7]: -``` +```py r = T.vector() new_r = T.set_subtensor(r[10:], 5) @@ -131,7 +131,7 @@ new_r = T.set_subtensor(r[10:], 5) In [8]: -``` +```py r = T.vector() new_r = T.inc_subtensor(r[10:], 5) diff --git a/docs/da/131.md b/docs/da/131.md index 02432a9be..268fc9a41 100644 --- a/docs/da/131.md +++ b/docs/da/131.md @@ -4,13 +4,13 @@ In [1]: -``` +```py import theano from theano import tensor as T ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -19,7 +19,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py # 两个整形三维张量 a, b = T.itensor3("a"), T.itensor3("b") @@ -30,7 +30,7 @@ a, b = T.itensor3("a"), T.itensor3("b") In [3]: -``` +```py print theano.pp(a + 3) # T.add(a, 3) -> itensor3 print theano.pp(3 - a) # T.sub(3, a) print theano.pp(a * 3.5) # T.mul(a, 3.5) -> ftensor3 or dtensor3 (depending on casting) @@ -41,7 +41,7 @@ print theano.pp(b % a) # T.mod(b, a) ``` -``` +```py (a + TensorConstant{3}) (TensorConstant{3} - a) (a * TensorConstant{3.5}) @@ -56,7 +56,7 @@ mod(b, a) In [4]: -``` +```py print theano.pp(a & b) # T.and_(a,b) bitwise and (alias T.bitwise_and) print theano.pp(a ^ 1) # T.xor(a,1) bitwise xor (alias T.bitwise_xor) print theano.pp(a | b) # T.or_(a,b) bitwise or (alias T.bitwise_or) @@ -64,7 +64,7 @@ print theano.pp(~a) # T.invert(a) bitwise invert (alias T.bitwise_not ``` -``` +```py and_(a, b) xor(a, TensorConstant{1}) or_(a, b) @@ -84,7 +84,7 @@ invert(a) In [5]: -``` +```py x = T.matrix() x_as_int = T.cast(x, 'int32') @@ -94,13 +94,13 @@ x_as_int = T.cast(x, 'int32') In [6]: -``` +```py print x_as_int is x print T.cast(x, theano.config.floatX) is x ``` -``` +```py False True @@ -128,14 +128,14 @@ True In [7]: -``` +```py x, y = T.dmatrices('x','y') print theano.pp(T.le(x, y)) ``` -``` +```py le(x, y) ``` @@ -159,7 +159,7 @@ le(x, y) In [8]: -``` +```py a, b = T.matrices("a", "b") print theano.pp(T.maximum(a, b)) # max(a, b) @@ -192,7 +192,7 @@ print theano.pp(T.psi(a)) # digamma(a) ``` -``` +```py maximum(a, b) minimum(a, b) (-a) @@ -240,7 +240,7 @@ $$ \operatorname{erf}(x) = \frac{2}{\sqrt\pi} \int_0^x e^{-t^2} dt $$$$ \begin{a In [9]: -``` +```py import numpy as np a = np.random.random((2,3,4)) @@ -272,7 +272,7 @@ print c.shape ``` -``` +```py (2, 3, 4) (5, 6, 4, 3) (2, 5, 6) diff --git a/docs/da/132.md b/docs/da/132.md index 5a63b4e9f..f4978de95 100644 --- a/docs/da/132.md +++ b/docs/da/132.md @@ -4,13 +4,13 @@ In [1]: -``` +```py import theano from theano import tensor as T ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled) ``` @@ -33,7 +33,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled) In [2]: -``` +```py x, y, b = T.dvectors('x', 'y', 'b') W = T.dmatrix('W') y = T.nnet.sigmoid(T.dot(W, x) + b) @@ -42,7 +42,7 @@ print theano.pprint(y) ``` -``` +```py sigmoid(((W \dot x) + b)) ``` @@ -57,7 +57,7 @@ $$\operatorname{softplus}(x) = \log_e{\left(1 + \exp(x)\right)}$$ In [3]: -``` +```py x,y,b = T.dvectors('x','y','b') W = T.dmatrix('W') y = T.nnet.softplus(T.dot(W,x) + b) @@ -66,7 +66,7 @@ print theano.pprint(y) ``` -``` +```py softplus(((W \dot x) + b)) ``` @@ -79,14 +79,14 @@ $$ \operatorname{softmax}_{ij}(x) = \frac{\exp{x_{ij}}}{\sum_k\exp(x_{ik})} $$ 不过,下面 的代码计算性能上更加稳定: -``` +```py e_x = exp(x - x.max(axis=1, keepdims=True)) out = e_x / e_x.sum(axis=1, keepdims=True) ``` In [4]: -``` +```py x,y,b = T.dvectors('x','y','b') W = T.dmatrix('W') y = T.nnet.softmax(T.dot(W,x) + b) @@ -95,7 +95,7 @@ print theano.pprint(y) ``` -``` +```py Softmax(((W \dot x) + b)) ``` @@ -110,7 +110,7 @@ $$ f(x_i) = \left\{ \begin{aligned} x_i, & \ x_i > 0 \\ \alpha x_i, & \ otherwis $$ \text{crossentropy}(t,o) = -(t\cdot log(o) + (1 - t) \cdot log(1 - o)) $$In [5]: -``` +```py x, y, b, c = T.dvectors('x', 'y', 'b', 'c') W = T.dmatrix('W') V = T.dmatrix('V') diff --git a/docs/da/133.md b/docs/da/133.md index 654ed9ea0..a9617e675 100644 --- a/docs/da/133.md +++ b/docs/da/133.md @@ -42,7 +42,7 @@ ## MNIST 卷积神经网络形状详解 -``` +```py def model(X, w, w2, w3, w4, p_drop_conv, p_drop_hidden): # X: 128 * 1 * 28 * 28 diff --git a/docs/da/135.md b/docs/da/135.md index 3ebbb6ff0..7f8f3a124 100644 --- a/docs/da/135.md +++ b/docs/da/135.md @@ -4,7 +4,7 @@ 最简单的方式是通过 [conda](http://conda.pydata.org/miniconda.html) 来进行安装: -``` +```py conda install basemap ``` @@ -16,7 +16,7 @@ conda install basemap In [2]: -``` +```py %matplotlib inline from mpl_toolkits.basemap import Basemap diff --git a/docs/da/136.md b/docs/da/136.md index 3d77c3057..a0c69764d 100644 --- a/docs/da/136.md +++ b/docs/da/136.md @@ -4,7 +4,7 @@ 最简单的方式是通过 [conda](http://conda.pydata.org/miniconda.html) 来进行安装: -``` +```py conda install -c scitools cartopy ``` @@ -16,7 +16,7 @@ conda install -c scitools cartopy In [1]: -``` +```py %matplotlib inline import cartopy.crs as ccrs diff --git a/docs/da/137.md b/docs/da/137.md index ff5e02647..2d36e7d4f 100644 --- a/docs/da/137.md +++ b/docs/da/137.md @@ -6,7 +6,7 @@ 使用 `pip` 安装: -``` +```py pip install py-goldsberry ``` @@ -14,7 +14,7 @@ pip install py-goldsberry In [1]: -``` +```py import goldsberry as gb import pandas as pd @@ -24,14 +24,14 @@ import pandas as pd In [2]: -``` +```py gb.__version__ ``` Out[2]: -``` +```py '0.8.0.1' ``` @@ -41,7 +41,7 @@ Out[2]: In [3]: -``` +```py players = gb.PlayerList().players() players = pd.DataFrame(players) @@ -63,12 +63,12 @@ Out[3]: In [4]: -``` +```py print len(players) ``` -``` +```py 464 ``` @@ -77,7 +77,7 @@ print len(players) In [5]: -``` +```py gsw_players = players.ix[players["TEAM_ABBREVIATION"] == "GSW"] gsw_players[["DISPLAY_LAST_COMMA_FIRST", "FROM_YEAR", "TEAM_ABBREVIATION", "TEAM_CITY", "TEAM_NAME", "PERSON_ID"]] @@ -110,7 +110,7 @@ Out[5]: In [6]: -``` +```py kobe = players.ix[players["DISPLAY_LAST_COMMA_FIRST"].str.contains("Kobe")] kobe @@ -127,7 +127,7 @@ Out[6]: In [7]: -``` +```py kobe_id = 977 ``` @@ -136,7 +136,7 @@ kobe_id = 977 In [8]: -``` +```py kobe_logs = gb.player.game_logs(kobe_id) kobe_logs = pd.DataFrame(kobe_logs.logs()) @@ -162,14 +162,14 @@ Out[8]: In [9]: -``` +```py kobe_logs.Game_ID ``` Out[9]: -``` +```py 0 0021500795 1 0021500776 2 0021500767 @@ -220,7 +220,7 @@ Name: Game_ID, dtype: object In [10]: -``` +```py def show_avg_info(avg): print "得分:{:.1f}".format(avg.ix["PTS"]) print "篮板:{:.1f}".format(avg.ix["REB"]) @@ -241,7 +241,7 @@ show_avg_info(kobe_logs.mean()) ``` -``` +```py 得分:16.9 篮板:4.2 助攻:3.4 @@ -263,7 +263,7 @@ show_avg_info(kobe_logs.mean()) In [11]: -``` +```py curry_id = 201939 curry_logs = gb.player.game_logs(curry_id) curry_logs = pd.DataFrame(curry_logs.logs()) @@ -272,7 +272,7 @@ show_avg_info(curry_logs.mean()) ``` -``` +```py 得分:29.8 篮板:5.3 助攻:6.6 @@ -294,7 +294,7 @@ show_avg_info(curry_logs.mean()) In [12]: -``` +```py kobe_career = gb.player.career_stats(kobe_id) curry_career = gb.player.career_stats(curry_id) @@ -304,7 +304,7 @@ curry_career = gb.player.career_stats(curry_id) In [13]: -``` +```py def show_career_high(career): career_high = pd.DataFrame(career.career_high()).ix[[0,1,5]] print career_high[["GAME_DATE", "STAT", "STAT_VALUE", "VS_TEAM_CITY", "VS_TEAM_NAME"]] @@ -317,7 +317,7 @@ show_career_high(curry_career) ``` -``` +```py Kobe GAME_DATE STAT STAT_VALUE VS_TEAM_CITY VS_TEAM_NAME 0 JAN 22 2006 PTS 81 Toronto Raptors @@ -335,7 +335,7 @@ Curry In [14]: -``` +```py def show_season_high(career): career_high = pd.DataFrame(career.season_high()).ix[[0,1,5]] print career_high[["GAME_DATE", "STAT", "STAT_VALUE", "VS_TEAM_CITY", "VS_TEAM_NAME"]] @@ -348,7 +348,7 @@ show_season_high(curry_career) ``` -``` +```py Kobe GAME_DATE STAT STAT_VALUE VS_TEAM_CITY VS_TEAM_NAME 0 FEB 02 2016 PTS 38 Minnesota Timberwolves @@ -366,7 +366,7 @@ Curry In [15]: -``` +```py game_ids = gb.GameIDs() game_ids = pd.DataFrame(game_ids.game_list()) @@ -390,7 +390,7 @@ Out[15]: In [16]: -``` +```py from IPython.display import Image Image("http://stats.nba.com/media/players/230x185/"+str(kobe_id)+".png") @@ -652,7 +652,7 @@ LQ1XLsqf/fX7A7Dknl88MA9/4Z83fExM8Ht+c+2mT/1/+saG7Vs2/7Hu+fDNA1uJ24evu+46DlF/ 5c8G4TdahtfBbxc1YQAAAABJRU5ErkJggg== )In [17]: -``` +```py Image("http://stats.nba.com/media/players/230x185/"+str(curry_id)+".png") ``` @@ -891,7 +891,7 @@ jIq5m9iujF1/a+y2049YJsLzcdvc3O3vTeVue3NQY4A//OJr7TY3vMTs73b1ds2+sGKq0/INEKxJ In [18]: -``` +```py from goldsberry.player import _Player as pl_old ``` @@ -900,7 +900,7 @@ from goldsberry.player import _Player as pl_old In [19]: -``` +```py players_1997 = pl_old.PlayerList(1997) players_1997 = pd.DataFrame(players_1997) @@ -911,7 +911,7 @@ players_1997 = pd.DataFrame(players_1997) In [20]: -``` +```py jordan_id = players_1997["PERSON_ID"].ix[players_1997["DISPLAY_LAST_COMMA_FIRST"].str.contains("Jordan, Michael")] jordan_id = jordan_id[jordan_id.index[0]] jordan_id @@ -920,7 +920,7 @@ jordan_id Out[20]: -``` +```py 893 ``` @@ -928,7 +928,7 @@ Out[20]: In [21]: -``` +```py jordan_logs_1997 = pl_old.game_logs(jordan_id, season="1997") jordan_logs_1997 = pd.DataFrame(jordan_logs_1997.logs()) @@ -936,7 +936,7 @@ show_avg_info(jordan_logs_1997.mean()) ``` -``` +```py 得分:28.7 篮板:5.8 助攻:3.5 @@ -958,7 +958,7 @@ show_avg_info(jordan_logs_1997.mean()) In [22]: -``` +```py jordan_logs_1997 = pl_old.game_logs(jordan_id, season="1997", seasontype=2) jordan_logs_1997 = pd.DataFrame(jordan_logs_1997.logs()) @@ -966,7 +966,7 @@ show_avg_info(jordan_logs_1997.mean()) ``` -``` +```py 得分:32.4 篮板:5.1 助攻:3.5 @@ -988,7 +988,7 @@ show_avg_info(jordan_logs_1997.mean()) In [23]: -``` +```py Image("http://stats.nba.com/media/players/230x185/"+str(jordan_id)+".png") ``` diff --git a/docs/da/138.md b/docs/da/138.md index 974fe8b42..af16205d8 100644 --- a/docs/da/138.md +++ b/docs/da/138.md @@ -28,7 +28,7 @@ In [1]: -``` +```py from __future__ import unicode_literals ``` @@ -37,7 +37,7 @@ from __future__ import unicode_literals In [2]: -``` +```py import numpy as np import scipy as sp import matplotlib.pyplot as plt @@ -159,7 +159,7 @@ TkSuQmCC 找到了字体的位置,我们可以使用 `matplotlib.font_manager` 中的 `FontProperties` 导入字体: -``` +```py font_xxx = FontProperties(fname="/usr/share/fonts/truetype/osx-font-family/Songti.ttc") font_xxx = FontProperties(fname="C://Windows//Fonts//simsum.ttc") ``` @@ -171,7 +171,7 @@ font_xxx = FontProperties(fname="C://Windows//Fonts//simsum.ttc") In [3]: -``` +```py from matplotlib.font_manager import FontProperties font_simsum = FontProperties(fname="simsun.ttc") @@ -183,7 +183,7 @@ font_yahei_consolas = FontProperties(fname="YaHei.Consolas.1.11b.ttf") In [4]: -``` +```py x = range(10) plt.plot(x) plt.title("中文", fontproperties=font_yahei_consolas, fontsize=14) @@ -293,12 +293,12 @@ AYjUkrBdjQAAAABJRU5ErkJggg== In [5]: -``` +```py !ls novels ``` -``` +```py 书剑恩仇录.txt 天龙八部.txt 碧血剑.txt 越女剑.txt 飞狐外传.txt 侠客行.txt 射雕英雄传.txt 神雕侠侣.txt 连城诀.txt 鸳鸯刀.txt 倚天屠龙记.txt 白马啸西风.txt 笑傲江湖.txt 雪山飞狐.txt 鹿鼎记.txt @@ -309,7 +309,7 @@ In [5]: In [6]: -``` +```py with open('novels/鸳鸯刀.txt') as f: # 去掉结尾的换行符 data = [line.strip().decode('utf8') for line in f.readlines()] @@ -320,7 +320,7 @@ for line in data[:13]: ``` -``` +```py   鸳鸯刀   四个劲装结束的汉子并肩而立,拦在当路! @@ -335,7 +335,7 @@ for line in data[:13]: 接着,我们先找到金庸小说中所有出场的人物,放到 names.txt 文件中,其格式为: -``` +```py 小说1 人物1 人物2 …… 小说2 @@ -347,7 +347,7 @@ for line in data[:13]: In [7]: -``` +```py with open('names.txt') as f: # 去掉结尾的换行符 data = [line.strip().decode('utf8') for line in f.readlines()] @@ -362,7 +362,7 @@ for name in novel_names['天龙八部'][:20]: ``` -``` +```py 刀白凤 丁春秋 马夫人 @@ -394,7 +394,7 @@ for name in novel_names['天龙八部'][:20]: In [8]: -``` +```py def find_main_charecters(novel, num=10): with open('novels/{}.txt'.format(novel)) as f: data = f.read().decode('utf8') @@ -417,7 +417,7 @@ def find_main_charecters(novel, num=10): In [9]: -``` +```py find_main_charecters("天龙八部") ``` @@ -624,7 +624,7 @@ rkJggg== In [10]: -``` +```py find_main_charecters("射雕英雄传") find_main_charecters("神雕侠侣") find_main_charecters("倚天屠龙记") @@ -1266,7 +1266,7 @@ RK5CYII= 首先安装 `gensim`: -``` +```py pip install gensim ``` @@ -1274,12 +1274,12 @@ pip install gensim In [11]: -``` +```py import gensim ``` -``` +```py Using gpu device 1: Tesla C2075 (CNMeM is disabled, CuDNN not available) ``` @@ -1294,7 +1294,7 @@ Using gpu device 1: Tesla C2075 (CNMeM is disabled, CuDNN not available) 安装 jieba: -``` +```py pip install jieba ``` @@ -1302,7 +1302,7 @@ pip install jieba In [12]: -``` +```py import jieba ``` @@ -1311,7 +1311,7 @@ import jieba In [13]: -``` +```py for _, names in novel_names.iteritems(): for name in names: jieba.add_word(name) @@ -1330,7 +1330,7 @@ for name in bang_names: ``` -``` +```py Building prefix dict from the default dictionary ... DEBUG:jieba:Building prefix dict from the default dictionary ... Loading model from cache /tmp/jieba.cache @@ -1346,7 +1346,7 @@ DEBUG:jieba:Prefix dict has been built succesfully. In [14]: -``` +```py novels = ["书剑恩仇录", "天龙八部", "碧血剑", @@ -1375,7 +1375,7 @@ for novel in novels: ``` -``` +```py 处理:书剑恩仇录 处理:天龙八部 处理:碧血剑 @@ -1400,7 +1400,7 @@ for novel in novels: In [15]: -``` +```py model = gensim.models.Word2Vec(sentences, size=100, window=5, min_count=5, workers=4) ``` @@ -1409,7 +1409,7 @@ model = gensim.models.Word2Vec(sentences, size=100, window=5, min_count=5, worke In [16]: -``` +```py model.save("louis_cha.model") ``` @@ -1418,7 +1418,7 @@ model.save("louis_cha.model") In [17]: -``` +```py model = gensim.models.Word2Vec.load("louis_cha.model") ``` @@ -1431,13 +1431,13 @@ model = gensim.models.Word2Vec.load("louis_cha.model") In [18]: -``` +```py for k, s in model.most_similar(positive=["乔峰", "萧峰"]): print k, s ``` -``` +```py 段正淳 0.839533925056 慕容复 0.800726354122 虚竹 0.796926677227 @@ -1457,13 +1457,13 @@ for k, s in model.most_similar(positive=["乔峰", "萧峰"]): In [19]: -``` +```py for k, s in model.most_similar(positive=["阿朱"]): print k, s ``` -``` +```py 钟灵 0.789930582047 阿紫 0.77720785141 方怡 0.774438858032 @@ -1483,13 +1483,13 @@ for k, s in model.most_similar(positive=["阿朱"]): In [20]: -``` +```py for k, s in model.most_similar(positive=["丐帮"]): print k, s ``` -``` +```py 长乐帮 0.807791054249 雪山派 0.793763160706 峨嵋派 0.792181968689 @@ -1509,13 +1509,13 @@ for k, s in model.most_similar(positive=["丐帮"]): In [21]: -``` +```py for k, s in model.most_similar(positive=["降龙十八掌"]): print k, s ``` -``` +```py 打狗棒法 0.89123404026 空明拳 0.890258312225 太极拳 0.884406626225 @@ -1533,7 +1533,7 @@ for k, s in model.most_similar(positive=["降龙十八掌"]): In [22]: -``` +```py def find_relationship(a, b, c): """ 返回 d @@ -1546,7 +1546,7 @@ find_relationship("段誉", "段公子", "乔峰") ``` -``` +```py 给定“段誉”与“段公子”,“乔峰”和“乔帮主”有类似的关系 ``` @@ -1555,7 +1555,7 @@ find_relationship("段誉", "段公子", "乔峰") In [23]: -``` +```py # 情侣对 find_relationship("郭靖", "黄蓉", "杨过") @@ -1567,7 +1567,7 @@ find_relationship("郭靖", "华筝", "杨过") ``` -``` +```py 给定“郭靖”与“黄蓉”,“杨过”和“小龙女”有类似的关系 给定“令狐冲”与“任我行”,“郭靖”和“黄药师”有类似的关系 给定“郭靖”与“华筝”,“杨过”和“绿萼”有类似的关系 @@ -1578,7 +1578,7 @@ find_relationship("郭靖", "华筝", "杨过") In [24]: -``` +```py # 韦小宝 find_relationship("杨过", "小龙女", "韦小宝") find_relationship("令狐冲", "盈盈", "韦小宝") @@ -1586,7 +1586,7 @@ find_relationship("张无忌", "赵敏", "韦小宝") ``` -``` +```py 给定“杨过”与“小龙女”,“韦小宝”和“康熙”有类似的关系 给定“令狐冲”与“盈盈”,“韦小宝”和“康熙”有类似的关系 给定“张无忌”与“赵敏”,“韦小宝”和“康熙”有类似的关系 @@ -1597,14 +1597,14 @@ find_relationship("张无忌", "赵敏", "韦小宝") In [25]: -``` +```py find_relationship("郭靖", "降龙十八掌", "黄蓉") find_relationship("武当", "张三丰", "少林") find_relationship("任我行", "魔教", "令狐冲") ``` -``` +```py 给定“郭靖”与“降龙十八掌”,“黄蓉”和“打狗棒法”有类似的关系 给定“武当”与“张三丰”,“少林”和“灭绝师太”有类似的关系 给定“任我行”与“魔教”,“令狐冲”和“恒山派”有类似的关系 @@ -1619,7 +1619,7 @@ find_relationship("任我行", "魔教", "令狐冲") In [26]: -``` +```py all_names = [] word_vectors = None @@ -1643,7 +1643,7 @@ all_names = np.array(all_names) In [27]: -``` +```py from sklearn.cluster import KMeans ``` @@ -1652,7 +1652,7 @@ from sklearn.cluster import KMeans In [28]: -``` +```py N = 3 label = KMeans(N).fit(word_vectors).labels_ @@ -1666,7 +1666,7 @@ for c in range(N): ``` -``` +```py 类别1: 刀白凤 丁春秋 马夫人 巴天石 邓百川 风波恶 公冶乾 包不同 乌老大 云中鹤 白世镜 本因 过彦之 司马林 玄慈 玄寂 玄难 叶二娘 左子穆 李秋水 @@ -1696,7 +1696,7 @@ for c in range(N): In [29]: -``` +```py N = 4 c = sp.stats.mode(label).mode remain_names = all_names[label!=c] @@ -1714,7 +1714,7 @@ for c in range(N): ``` -``` +```py 类别1: 刀白凤 马夫人 风波恶 包不同 乌老大 白世镜 司马林 叶二娘 左子穆 李秋水 阮星竹 阿碧 苏星河 赵钱孙 钟万仇 秦红棉 崔百泉 萧远山 慕容博 谭婆 @@ -1740,7 +1740,7 @@ for c in range(N): In [30]: -``` +```py all_names = [] word_vectors = None @@ -1760,14 +1760,14 @@ all_names = np.array(all_names) In [31]: -``` +```py import scipy.cluster.hierarchy as sch ``` In [32]: -``` +```py Y = sch.linkage(word_vectors, method="ward") _, ax = plt.subplots(figsize=(10, 40)) @@ -3420,7 +3420,7 @@ w4+IiIjoGC0N5CQdDFwM7Gn7z9XpvwKvlfRT4FpgaYb2/tq6wG2U7N1TwM3Az21vBnwY+KSkrzdz In [33]: -``` +```py all_names = [] word_vectors = None for name in kungfu_names: @@ -5216,7 +5216,7 @@ hsKgKUmSpKEwaEqSJGko/gMmlSG9Jv7dsQAAAABJRU5ErkJggg== In [34]: -``` +```py all_names = [] word_vectors = None for name in bang_names: diff --git a/docs/da/140.md b/docs/da/140.md index 3b98a2d82..c75736a95 100644 --- a/docs/da/140.md +++ b/docs/da/140.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import pprint ``` @@ -13,7 +13,7 @@ import pprint In [2]: -``` +```py data = ( "this is a string", [1, 2, 3, 4], @@ -27,12 +27,12 @@ data = ( In [3]: -``` +```py print data ``` -``` +```py ('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), 'this is yet another string') ``` @@ -41,12 +41,12 @@ print data In [4]: -``` +```py pprint.pprint(data) ``` -``` +```py ('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), diff --git a/docs/da/141.md b/docs/da/141.md index 88ce3199d..c09e1512c 100644 --- a/docs/da/141.md +++ b/docs/da/141.md @@ -8,7 +8,7 @@ In [1]: -``` +```py try: import cPickle as pickle except: @@ -22,7 +22,7 @@ except: In [2]: -``` +```py data = [ { 'a':'A', 'b':2, 'c':3.0 } ] data_string = pickle.dumps(data) @@ -34,7 +34,7 @@ print data_string ``` -``` +```py DATA: [{'a': 'A', 'c': 3.0, 'b': 2}] PICKLE: @@ -54,14 +54,14 @@ sa. In [3]: -``` +```py data_from_string = pickle.loads(data_string) print data_from_string ``` -``` +```py [{'a': 'A', 'c': 3.0, 'b': 2}] ``` @@ -78,12 +78,12 @@ print data_from_string In [4]: -``` +```py print pickle.HIGHEST_PROTOCOL ``` -``` +```py 2 ``` @@ -92,7 +92,7 @@ print pickle.HIGHEST_PROTOCOL In [5]: -``` +```py data_string_1 = pickle.dumps(data, 1) print "Pickle 1:", data_string_1 @@ -103,7 +103,7 @@ print "Pickle 2:", data_string_2 ``` -``` +```py Pickle 1: ]q�}q�(U�aU�AU�cG@�U�bK�ua. Pickle 2: ��]q�}q�(U�aU�AU�cG@�U�bK�ua. @@ -113,12 +113,12 @@ Pickle 2: ��]q�}q�(U�aU�AU�cG@�U�bK�ua. In [6]: -``` +```py print pickle.dumps(data, -1) ``` -``` +```py ��]q�}q�(U�aU�AU�cG@�U�bK�ua. ``` @@ -127,13 +127,13 @@ print pickle.dumps(data, -1) In [7]: -``` +```py print "Load 1:", pickle.loads(data_string_1) print "Load 2:", pickle.loads(data_string_2) ``` -``` +```py Load 1: [{'a': 'A', 'c': 3.0, 'b': 2}] Load 2: [{'a': 'A', 'c': 3.0, 'b': 2}] @@ -152,7 +152,7 @@ Load 2: [{'a': 'A', 'c': 3.0, 'b': 2}] In [8]: -``` +```py with open("data.pkl", "wb") as f: pickle.dump(data, f) @@ -162,7 +162,7 @@ with open("data.pkl", "wb") as f: In [9]: -``` +```py with open("data.pkl") as f: data_from_file = pickle.load(f) @@ -170,7 +170,7 @@ print data_from_file ``` -``` +```py [{'a': 'A', 'c': 3.0, 'b': 2}] ``` @@ -179,7 +179,7 @@ print data_from_file In [10]: -``` +```py import os os.remove("data.pkl") diff --git a/docs/da/142.md b/docs/da/142.md index 00a2c2d0a..4691e200b 100644 --- a/docs/da/142.md +++ b/docs/da/142.md @@ -24,7 +24,7 @@ 例子: -``` +```py { "name": "echo", "age": 24, @@ -47,7 +47,7 @@ In [1]: -``` +```py import json from pprint import pprint @@ -73,14 +73,14 @@ info_string = """ In [2]: -``` +```py info = json.loads(info_string) pprint(info) ``` -``` +```py {u'age': 24, u'ages for school': {u'high school': 15, u'middle school': 9, @@ -103,14 +103,14 @@ pprint(info) In [3]: -``` +```py type(info) ``` Out[3]: -``` +```py dict ``` @@ -118,14 +118,14 @@ dict In [4]: -``` +```py info_json = json.dumps(info) print info_json ``` -``` +```py {"name": "echo", "age": 24, "married": false, "ages for school": {"middle school": 9, "university": 18, "high school": 15, "primary school": 6}, "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"], "hobby": ["sports", "reading"]} ``` @@ -141,7 +141,7 @@ print info_json In [5]: -``` +```py with open("info.json", "w") as f: json.dump(info, f) @@ -151,13 +151,13 @@ with open("info.json", "w") as f: In [6]: -``` +```py with open("info.json") as f: print f.read() ``` -``` +```py {"name": "echo", "age": 24, "married": false, "ages for school": {"middle school": 9, "university": 18, "high school": 15, "primary school": 6}, "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"], "hobby": ["sports", "reading"]} ``` @@ -166,7 +166,7 @@ with open("info.json") as f: In [7]: -``` +```py with open("info.json") as f: info_from_file = json.load(f) @@ -174,7 +174,7 @@ pprint(info_from_file) ``` -``` +```py {u'age': 24, u'ages for school': {u'high school': 15, u'middle school': 9, @@ -197,7 +197,7 @@ pprint(info_from_file) In [8]: -``` +```py import os os.remove("info.json") diff --git a/docs/da/143.md b/docs/da/143.md index fe36cf158..a7b69ed3e 100644 --- a/docs/da/143.md +++ b/docs/da/143.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import glob ``` @@ -13,14 +13,14 @@ import glob In [2]: -``` +```py glob.glob("*.ipynb") ``` Out[2]: -``` +```py ['11.03 json.ipynb', '11.01 pprint.ipynb', '11.02 pickle and cpickle.ipynb', @@ -37,14 +37,14 @@ Out[2]: In [3]: -``` +```py glob.glob("../09*/*.ipynb") ``` Out[3]: -``` +```py ['../09\. theano/09.05 configuration settings and compiling modes.ipynb', '../09\. theano/09.03 gpu on windows.ipynb', '../09\. theano/09.07 loop with scan.ipynb', @@ -66,14 +66,14 @@ Out[3]: In [4]: -``` +```py glob.glob("../[0-9]*") ``` Out[4]: -``` +```py ['../04\. scipy', '../02\. python essentials', '../07\. interfacing with other languages', diff --git a/docs/da/144.md b/docs/da/144.md index 6f8407024..6f99e5a11 100644 --- a/docs/da/144.md +++ b/docs/da/144.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import shutil import os @@ -14,7 +14,7 @@ import os In [2]: -``` +```py with open("test.file", "w") as f: pass @@ -22,7 +22,7 @@ print "test.file" in os.listdir(os.curdir) ``` -``` +```py True ``` @@ -31,7 +31,7 @@ True In [3]: -``` +```py shutil.copy("test.file", "test.copy.file") print "test.file" in os.listdir(os.curdir) @@ -39,7 +39,7 @@ print "test.copy.file" in os.listdir(os.curdir) ``` -``` +```py True True @@ -49,7 +49,7 @@ True In [4]: -``` +```py try: shutil.copy("test.file", "my_test_dir/test.copy.file") except IOError as msg: @@ -57,7 +57,7 @@ except IOError as msg: ``` -``` +```py [Errno 2] No such file or directory: 'my_test_dir/test.copy.file' ``` @@ -70,7 +70,7 @@ except IOError as msg: In [5]: -``` +```py os.renames("test.file", "test_dir/test.file") os.renames("test.copy.file", "test_dir/test.copy.file") @@ -80,7 +80,7 @@ os.renames("test.copy.file", "test_dir/test.copy.file") In [6]: -``` +```py shutil.copytree("test_dir/", "test_dir_copy/") "test_dir_copy" in os.listdir(os.curdir) @@ -89,7 +89,7 @@ shutil.copytree("test_dir/", "test_dir_copy/") Out[6]: -``` +```py True ``` @@ -99,7 +99,7 @@ True In [7]: -``` +```py try: os.removedirs("test_dir_copy") except Exception as msg: @@ -107,7 +107,7 @@ except Exception as msg: ``` -``` +```py [Errno 39] Directory not empty: 'test_dir_copy' ``` @@ -116,7 +116,7 @@ except Exception as msg: In [8]: -``` +```py shutil.rmtree("test_dir_copy") ``` @@ -131,14 +131,14 @@ shutil.rmtree("test_dir_copy") In [9]: -``` +```py shutil.get_archive_formats() ``` Out[9]: -``` +```py [('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), @@ -151,14 +151,14 @@ Out[9]: In [10]: -``` +```py shutil.make_archive("test_archive", "zip", "test_dir/") ``` Out[10]: -``` +```py '/home/lijin/notes-python/11\. useful tools/test_archive.zip' ``` @@ -166,7 +166,7 @@ Out[10]: In [11]: -``` +```py os.remove("test_archive.zip") shutil.rmtree("test_dir/") diff --git a/docs/da/145.md b/docs/da/145.md index a454374cf..3076a9fc0 100644 --- a/docs/da/145.md +++ b/docs/da/145.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import os, shutil, glob import zlib, gzip, bz2, zipfile, tarfile @@ -16,7 +16,7 @@ gzip In [2]: -``` +```py orginal = "this is a test string" compressed = zlib.compress(orginal) @@ -26,7 +26,7 @@ print zlib.decompress(compressed) ``` -``` +```py x�+��,V�D������⒢̼tS��� this is a test string @@ -36,24 +36,24 @@ this is a test string In [3]: -``` +```py print zlib.adler32(orginal) & 0xffffffff ``` -``` +```py 1407780813 ``` In [4]: -``` +```py print zlib.crc32(orginal) & 0xffffffff ``` -``` +```py 4236695221 ``` @@ -66,7 +66,7 @@ print zlib.crc32(orginal) & 0xffffffff In [5]: -``` +```py content = "Lots of content here" with gzip.open('file.txt.gz', 'wb') as f: f.write(content) @@ -77,7 +77,7 @@ with gzip.open('file.txt.gz', 'wb') as f: In [6]: -``` +```py with gzip.open('file.txt.gz', 'rb') as f: file_content = f.read() @@ -85,7 +85,7 @@ print file_content ``` -``` +```py Lots of content here ``` @@ -94,7 +94,7 @@ Lots of content here In [7]: -``` +```py with gzip.open('file.txt.gz', 'rb') as f_in, open('file.txt', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) @@ -104,20 +104,20 @@ with gzip.open('file.txt.gz', 'rb') as f_in, open('file.txt', 'wb') as f_out: In [8]: -``` +```py with open("file.txt") as f: print f.read() ``` -``` +```py Lots of content here ``` In [9]: -``` +```py os.remove("file.txt.gz") ``` @@ -128,7 +128,7 @@ os.remove("file.txt.gz") In [10]: -``` +```py orginal = "this is a test string" compressed = bz2.compress(orginal) @@ -138,7 +138,7 @@ print bz2.decompress(compressed) ``` -``` +```py BZh91AY&SY*��v ��@"�� 10"zi�����FLT`�軒)„�P�˰ this is a test string @@ -150,7 +150,7 @@ this is a test string In [11]: -``` +```py for i in range(10): shutil.copy("file.txt", "file.txt." + str(i)) @@ -160,7 +160,7 @@ for i in range(10): In [12]: -``` +```py f = zipfile.ZipFile('files.zip','w') for name in glob.glob("*.txt.[0-9]"): @@ -175,13 +175,13 @@ f.close() In [13]: -``` +```py f = zipfile.ZipFile('files.zip','r') print f.namelist() ``` -``` +```py ['file.txt.9', 'file.txt.6', 'file.txt.2', 'file.txt.1', 'file.txt.5', 'file.txt.4', 'file.txt.3', 'file.txt.7', 'file.txt.8', 'file.txt.0'] ``` @@ -190,7 +190,7 @@ print f.namelist() In [14]: -``` +```py for name in f.namelist(): print name, "content:", f.read(name) @@ -198,7 +198,7 @@ f.close() ``` -``` +```py file.txt.9 content: Lots of content here file.txt.6 content: Lots of content here file.txt.2 content: Lots of content here @@ -222,7 +222,7 @@ file.txt.0 content: Lots of content here In [15]: -``` +```py f = tarfile.open("file.txt.tar", "w") f.add("file.txt") f.close() @@ -233,7 +233,7 @@ f.close() In [16]: -``` +```py os.remove("file.txt") os.remove("file.txt.tar") os.remove("files.zip") diff --git a/docs/da/146.md b/docs/da/146.md index 0f3a89902..0d54d791d 100644 --- a/docs/da/146.md +++ b/docs/da/146.md @@ -4,7 +4,7 @@ In [1]: -``` +```py import logging ``` @@ -23,7 +23,7 @@ import logging In [2]: -``` +```py logging.critical('This is critical message') logging.error('This is error message') logging.warning('This is warning message') @@ -34,7 +34,7 @@ logging.debug('This is debug message') ``` -``` +```py CRITICAL:root:This is critical message ERROR:root:This is error message WARNING:root:This is warning message @@ -45,14 +45,14 @@ WARNING:root:This is warning message In [3]: -``` +```py logging.root.setLevel(level=logging.INFO) logging.info('This is info message') ``` -``` +```py INFO:root:This is info message ``` @@ -61,7 +61,7 @@ INFO:root:This is info message In [4]: -``` +```py logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s') logger = logging.getLogger("this program") @@ -70,7 +70,7 @@ logger.critical('This is critical message') ``` -``` +```py CRITICAL:this program:This is critical message ``` \ No newline at end of file diff --git a/docs/da/147.md b/docs/da/147.md index 8be2a6118..ed8446533 100644 --- a/docs/da/147.md +++ b/docs/da/147.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import string ``` @@ -11,14 +11,14 @@ import string In [2]: -``` +```py string.punctuation ``` Out[2]: -``` +```py '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` @@ -26,13 +26,13 @@ Out[2]: In [3]: -``` +```py print string.letters print string.ascii_letters ``` -``` +```py ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ @@ -42,7 +42,7 @@ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ In [4]: -``` +```py print string.ascii_lowercase print string.lowercase @@ -51,7 +51,7 @@ print string.uppercase ``` -``` +```py abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ @@ -61,12 +61,12 @@ ABCDEFGHIJKLMNOPQRSTUVWXYZ In [5]: -``` +```py print string.lower ``` -``` +```py ``` @@ -75,14 +75,14 @@ print string.lower In [6]: -``` +```py string.digits ``` Out[6]: -``` +```py '0123456789' ``` @@ -90,14 +90,14 @@ Out[6]: In [7]: -``` +```py string.hexdigits ``` Out[7]: -``` +```py '0123456789abcdefABCDEF' ``` @@ -105,14 +105,14 @@ Out[7]: In [8]: -``` +```py string.capwords("this is a big world") ``` Out[8]: -``` +```py 'This Is A Big World' ``` @@ -120,13 +120,13 @@ Out[8]: In [9]: -``` +```py string.center("test", 20) ``` Out[9]: -``` +```py ' test ' ``` \ No newline at end of file diff --git a/docs/da/148.md b/docs/da/148.md index 597176c5a..d6144e181 100644 --- a/docs/da/148.md +++ b/docs/da/148.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import collections ``` @@ -15,7 +15,7 @@ import collections In [2]: -``` +```py from string import punctuation sentence = "One, two, three, one, two, tree, I come from China." @@ -26,7 +26,7 @@ print words_count ``` -``` +```py Counter({'two': 2, 'one': 2, 'from': 1, 'i': 1, 'tree': 1, 'three': 1, 'china': 1, 'come': 1}) ``` @@ -37,7 +37,7 @@ Counter({'two': 2, 'one': 2, 'from': 1, 'i': 1, 'tree': 1, 'three': 1, 'china': In [3]: -``` +```py dq = collections.deque() for i in xrange(10): @@ -60,7 +60,7 @@ for i in xrange(10): ``` -``` +```py deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 9 8 7 6 5 4 3 2 1 0 deque([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) @@ -72,7 +72,7 @@ deque([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) In [4]: -``` +```py lst = [] dq = collections.deque() @@ -81,7 +81,7 @@ dq = collections.deque() ``` -``` +```py 100 loops, best of 3: 598 ns per loop 100 loops, best of 3: 291 ns per loop @@ -93,7 +93,7 @@ dq = collections.deque() In [5]: -``` +```py items = ( ('A', 1), ('B', 2), @@ -113,7 +113,7 @@ for k, v in ordered_dict.items(): ``` -``` +```py Regular Dict: A 1 C 3 @@ -131,7 +131,7 @@ C 3 In [6]: -``` +```py dd = collections.defaultdict(list) print dd["foo"] @@ -146,7 +146,7 @@ print dd["foo"] ``` -``` +```py [] 0 0.0 diff --git a/docs/da/149.md b/docs/da/149.md index 0b2ca0ab7..5de68693f 100644 --- a/docs/da/149.md +++ b/docs/da/149.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import requests ``` @@ -13,7 +13,7 @@ Python 标准库中的 `urllib2` 模块提供了你所需要的大多数 `HTTP` In [2]: -``` +```py r = requests.get("http://httpbin.org/get") r = requests.post('http://httpbin.org/post', data = {'key':'value'}) r = requests.put("http://httpbin.org/put") @@ -29,7 +29,7 @@ r = requests.options("http://httpbin.org/get") In [3]: -``` +```py payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params=payload) @@ -39,12 +39,12 @@ r = requests.get("http://httpbin.org/get", params=payload) In [4]: -``` +```py print(r.url) ``` -``` +```py http://httpbin.org/get?key2=value2&key1=value1 ``` @@ -55,14 +55,14 @@ http://httpbin.org/get?key2=value2&key1=value1 In [5]: -``` +```py r = requests.get('https://github.com/timeline.json') print r.text ``` -``` +```py {"message":"Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"} ``` @@ -71,14 +71,14 @@ print r.text In [6]: -``` +```py r.encoding ``` Out[6]: -``` +```py 'utf-8' ``` @@ -86,7 +86,7 @@ Out[6]: In [7]: -``` +```py r.encoding = "ISO-8859-1" r.text @@ -95,7 +95,7 @@ r.text Out[7]: -``` +```py u'{"message":"Hello there, wayfaring stranger. If you\xe2\x80\x99re reading this then you probably didn\xe2\x80\x99t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}' ``` @@ -103,14 +103,14 @@ u'{"message":"Hello there, wayfaring stranger. If you\xe2\x80\x99re reading this In [8]: -``` +```py r.json() ``` Out[8]: -``` +```py {u'documentation_url': u'https://developer.github.com/v3/activity/events/#list-public-events', u'message': u'Hello there, wayfaring stranger. If you\xe2\x80\x99re reading this then you probably didn\xe2\x80\x99t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.'} ``` @@ -121,7 +121,7 @@ Out[8]: In [9]: -``` +```py r = requests.get('http://httpbin.org/get') r.status_code @@ -130,7 +130,7 @@ r.status_code Out[9]: -``` +```py 407 ``` @@ -138,13 +138,13 @@ Out[9]: In [10]: -``` +```py r.headers['Content-Type'] ``` Out[10]: -``` +```py 'text/html' ``` \ No newline at end of file diff --git a/docs/da/151.md b/docs/da/151.md index 655b2aa10..9a52633c3 100644 --- a/docs/da/151.md +++ b/docs/da/151.md @@ -6,7 +6,7 @@ In [1]: -``` +```py %matplotlib inline import pandas as pd @@ -32,14 +32,14 @@ import matplotlib.pyplot as plt In [2]: -``` +```py s = pd.Series([1,3,5,np.nan,6,8]) print s ``` -``` +```py 0 1 1 3 2 5 @@ -58,14 +58,14 @@ dtype: float64 In [3]: -``` +```py dates = pd.date_range('20130101', periods=6) print dates ``` -``` +```py DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05', '2013-01-06'], dtype='datetime64[ns]', freq='D') @@ -76,7 +76,7 @@ DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', In [4]: -``` +```py df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) df @@ -100,7 +100,7 @@ Out[4]: In [5]: -``` +```py df2 = pd.DataFrame({'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), @@ -127,14 +127,14 @@ Out[5]: In [6]: -``` +```py df2.dtypes ``` Out[6]: -``` +```py A float64 B datetime64[ns] C float32 @@ -152,7 +152,7 @@ dtype: object In [7]: -``` +```py df.head() ``` @@ -171,7 +171,7 @@ Out[7]: In [8]: -``` +```py df.tail(3) ``` @@ -190,14 +190,14 @@ Out[8]: In [9]: -``` +```py df.index ``` Out[9]: -``` +```py DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05', '2013-01-06'], dtype='datetime64[ns]', freq='D') @@ -207,14 +207,14 @@ DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', In [10]: -``` +```py df.columns ``` Out[10]: -``` +```py Index([u'A', u'B', u'C', u'D'], dtype='object') ``` @@ -222,14 +222,14 @@ Index([u'A', u'B', u'C', u'D'], dtype='object') In [11]: -``` +```py df.values ``` Out[11]: -``` +```py array([[-0.60593585, -0.86165752, -1.00192387, 1.52858443], [-0.16540784, 0.38833783, 1.18718697, 1.81981793], [ 0.06525454, -1.60807414, -1.2823306 , -0.28606716], @@ -244,7 +244,7 @@ array([[-0.60593585, -0.86165752, -1.00192387, 1.52858443], In [12]: -``` +```py df.describe() ``` @@ -266,7 +266,7 @@ Out[12]: In [13]: -``` +```py df.T ``` @@ -286,7 +286,7 @@ Out[13]: In [14]: -``` +```py df.sort_index(ascending=False) ``` @@ -304,7 +304,7 @@ Out[14]: In [15]: -``` +```py df.sort_index(axis=1, ascending=False) ``` @@ -324,7 +324,7 @@ Out[15]: In [16]: -``` +```py df.sort_values(by="B") ``` @@ -350,14 +350,14 @@ Out[16]: In [17]: -``` +```py df["A"] ``` Out[17]: -``` +```py 2013-01-01 -0.605936 2013-01-02 -0.165408 2013-01-03 0.065255 @@ -371,14 +371,14 @@ Freq: D, Name: A, dtype: float64 In [18]: -``` +```py df.A ``` Out[18]: -``` +```py 2013-01-01 -0.605936 2013-01-02 -0.165408 2013-01-03 0.065255 @@ -392,7 +392,7 @@ Freq: D, Name: A, dtype: float64 In [19]: -``` +```py df[0:3] ``` @@ -409,7 +409,7 @@ Out[19]: In [20]: -``` +```py df["20130101":"20130103"] ``` @@ -428,14 +428,14 @@ Out[20]: In [21]: -``` +```py df.loc[dates[0]] ``` Out[21]: -``` +```py A -0.605936 B -0.861658 C -1.001924 @@ -447,7 +447,7 @@ Name: 2013-01-01 00:00:00, dtype: float64 In [22]: -``` +```py df.loc[:,['A','B']] ``` @@ -467,7 +467,7 @@ Out[22]: In [23]: -``` +```py df.loc['20130102':'20130104',['A','B']] ``` @@ -484,14 +484,14 @@ Out[23]: In [24]: -``` +```py df.loc['20130102',['A','B']] ``` Out[24]: -``` +```py A -0.165408 B 0.388338 Name: 2013-01-02 00:00:00, dtype: float64 @@ -501,14 +501,14 @@ Name: 2013-01-02 00:00:00, dtype: float64 In [25]: -``` +```py df.loc[dates[0],'B'] ``` Out[25]: -``` +```py -0.86165751902832299 ``` @@ -516,7 +516,7 @@ Out[25]: In [26]: -``` +```py %timeit -n100 df.loc[dates[0],'B'] %timeit -n100 df.at[dates[0],'B'] @@ -524,7 +524,7 @@ print df.at[dates[0],'B'] ``` -``` +```py 100 loops, best of 3: 329 µs per loop 100 loops, best of 3: 31.1 µs per loop -0.861657519028 @@ -537,14 +537,14 @@ print df.at[dates[0],'B'] In [27]: -``` +```py df.iloc[3] ``` Out[27]: -``` +```py A 1.289305 B 0.497115 C -0.225351 @@ -556,7 +556,7 @@ Name: 2013-01-04 00:00:00, dtype: float64 In [28]: -``` +```py df.iloc[3:5,0:2] ``` @@ -572,7 +572,7 @@ Out[28]: In [29]: -``` +```py df.iloc[[1,2,4],[0,2]] ``` @@ -589,7 +589,7 @@ Out[29]: In [30]: -``` +```py df.iloc[1:3,:] ``` @@ -605,7 +605,7 @@ Out[30]: In [31]: -``` +```py df.iloc[:, 1:3] ``` @@ -625,14 +625,14 @@ Out[31]: In [32]: -``` +```py df.iloc[1,1] ``` Out[32]: -``` +```py 0.3883378290420279 ``` @@ -640,7 +640,7 @@ Out[32]: In [33]: -``` +```py %timeit -n100 df.iloc[1,1] %timeit -n100 df.iat[1,1] @@ -648,7 +648,7 @@ df.iat[1,1] ``` -``` +```py 100 loops, best of 3: 236 µs per loop 100 loops, best of 3: 14.5 µs per loop @@ -656,7 +656,7 @@ df.iat[1,1] Out[33]: -``` +```py 0.3883378290420279 ``` @@ -666,7 +666,7 @@ Out[33]: In [34]: -``` +```py df[df.A > 0] ``` @@ -683,7 +683,7 @@ Out[34]: In [35]: -``` +```py df[df > 0] ``` @@ -703,7 +703,7 @@ Out[35]: In [36]: -``` +```py df2 = df.copy() df2['E'] = ['one', 'one','two','three','four','three'] @@ -724,7 +724,7 @@ Out[36]: In [37]: -``` +```py df2[df2['E'].isin(['two','four'])] ``` @@ -740,7 +740,7 @@ Out[37]: In [38]: -``` +```py s1 = pd.Series([1,2,3,4,5,6], index=pd.date_range('20130102', periods=6)) s1 @@ -749,7 +749,7 @@ s1 Out[38]: -``` +```py 2013-01-02 1 2013-01-03 2 2013-01-04 3 @@ -763,7 +763,7 @@ Freq: D, dtype: int64 In [39]: -``` +```py df['F'] = s1 df @@ -785,7 +785,7 @@ Out[39]: In [40]: -``` +```py df.at[dates[0],'A'] = 0 df @@ -805,7 +805,7 @@ Out[40]: In [41]: -``` +```py df.iat[0, 1] = 0 df @@ -827,7 +827,7 @@ Out[41]: In [42]: -``` +```py df.loc[:,'D'] = np.array([5] * len(df)) df @@ -849,7 +849,7 @@ Out[42]: In [43]: -``` +```py df2 = df.copy() df2[df2 > 0] = -df2 @@ -873,7 +873,7 @@ Out[43]: In [44]: -``` +```py df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E']) df1.loc[dates[0]:dates[1],'E'] = 1 @@ -894,7 +894,7 @@ Out[44]: In [45]: -``` +```py df1.dropna(how='any') ``` @@ -909,7 +909,7 @@ Out[45]: In [46]: -``` +```py df1.fillna(value=5) ``` @@ -927,7 +927,7 @@ Out[46]: In [47]: -``` +```py pd.isnull(df1) ``` @@ -949,14 +949,14 @@ Out[47]: In [48]: -``` +```py df.mean() ``` Out[48]: -``` +```py A -0.156012 B 0.023693 C 0.047490 @@ -969,14 +969,14 @@ dtype: float64 In [49]: -``` +```py df.mean(1) ``` Out[49]: -``` +```py 2013-01-01 0.999519 2013-01-02 1.482023 2013-01-03 0.834970 @@ -990,14 +990,14 @@ Freq: D, dtype: float64 In [50]: -``` +```py s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2) print s ``` -``` +```py 2013-01-01 NaN 2013-01-02 NaN 2013-01-03 1 @@ -1012,7 +1012,7 @@ Freq: D, dtype: float64 In [51]: -``` +```py df.sub(s, axis='index') ``` @@ -1034,7 +1034,7 @@ Out[51]: In [52]: -``` +```py df.apply(np.cumsum) ``` @@ -1054,14 +1054,14 @@ Out[52]: In [53]: -``` +```py df.apply(lambda x: x.max() - x.min()) ``` Out[53]: -``` +```py A 3.452758 B 2.483131 C 2.982217 @@ -1074,13 +1074,13 @@ dtype: float64 In [54]: -``` +```py s = pd.Series(np.random.randint(0, 7, size=10)) print s ``` -``` +```py 0 2 1 5 2 6 @@ -1099,12 +1099,12 @@ dtype: int64 In [55]: -``` +```py print s.value_counts() ``` -``` +```py 6 3 5 2 4 2 @@ -1119,7 +1119,7 @@ dtype: int64 In [56]: -``` +```py h = s.hist() ``` @@ -1230,14 +1230,14 @@ AwAAAABJRU5ErkJggg== In [57]: -``` +```py s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat']) print s.str.lower() ``` -``` +```py 0 a 1 b 2 c @@ -1257,7 +1257,7 @@ dtype: object In [58]: -``` +```py df = pd.DataFrame(np.random.randn(10, 4)) df @@ -1283,7 +1283,7 @@ Out[58]: In [59]: -``` +```py pieces = [df[:2], df[4:5], df[7:]] pd.concat(pieces) @@ -1307,7 +1307,7 @@ Out[59]: In [60]: -``` +```py left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]}) right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]}) @@ -1316,7 +1316,7 @@ print right ``` -``` +```py key lval 0 foo 1 1 foo 2 @@ -1328,7 +1328,7 @@ print right In [61]: -``` +```py pd.merge(left, right, on='key') ``` @@ -1348,7 +1348,7 @@ Out[61]: In [62]: -``` +```py df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D']) df @@ -1372,7 +1372,7 @@ Out[62]: In [63]: -``` +```py s = df.iloc[3] df.append(s, ignore_index=True) @@ -1397,7 +1397,7 @@ Out[63]: In [64]: -``` +```py df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', @@ -1426,7 +1426,7 @@ Out[64]: In [65]: -``` +```py df.groupby('A').sum() ``` @@ -1444,7 +1444,7 @@ Out[65]: In [66]: -``` +```py df.groupby(['A', 'B']).sum() ``` @@ -1470,7 +1470,7 @@ Out[66]: In [67]: -``` +```py tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', @@ -1502,7 +1502,7 @@ Out[67]: In [68]: -``` +```py df2 = df[:4] stacked = df2.stack() @@ -1513,7 +1513,7 @@ stacked Out[68]: -``` +```py first second bar one A -0.109174 B 0.958551 @@ -1530,7 +1530,7 @@ dtype: float64 In [69]: -``` +```py stacked.unstack() ``` @@ -1550,7 +1550,7 @@ Out[69]: In [70]: -``` +```py stacked.unstack(1) ``` @@ -1572,7 +1572,7 @@ Out[70]: In [71]: -``` +```py rng = pd.date_range('3/6/2012 00:00', periods=5, freq='D') ts = pd.Series(np.random.randn(len(rng)), rng) @@ -1582,7 +1582,7 @@ ts Out[71]: -``` +```py 2012-03-06 1.096788 2012-03-07 0.029678 2012-03-08 0.511461 @@ -1595,7 +1595,7 @@ Freq: D, dtype: float64 In [72]: -``` +```py ts_utc = ts.tz_localize('UTC') ts_utc @@ -1604,7 +1604,7 @@ ts_utc Out[72]: -``` +```py 2012-03-06 00:00:00+00:00 1.096788 2012-03-07 00:00:00+00:00 0.029678 2012-03-08 00:00:00+00:00 0.511461 @@ -1619,14 +1619,14 @@ In [ ]: In [73]: -``` +```py ts_utc.tz_convert('US/Eastern') ``` Out[73]: -``` +```py 2012-03-05 19:00:00-05:00 1.096788 2012-03-06 19:00:00-05:00 0.029678 2012-03-07 19:00:00-05:00 0.511461 @@ -1639,7 +1639,7 @@ Freq: D, dtype: float64 In [74]: -``` +```py df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']}) df @@ -1661,7 +1661,7 @@ Out[74]: In [75]: -``` +```py df["grade"] = df["raw_grade"].astype("category") df["grade"] @@ -1670,7 +1670,7 @@ df["grade"] Out[75]: -``` +```py 0 a 1 b 2 b @@ -1685,7 +1685,7 @@ Categories (3, object): [a, b, e] In [76]: -``` +```py df["grade"].cat.categories = ["very good", "good", "very bad"] df["grade"] @@ -1694,7 +1694,7 @@ df["grade"] Out[76]: -``` +```py 0 very good 1 good 2 good @@ -1709,7 +1709,7 @@ Categories (3, object): [very good, good, very bad] In [77]: -``` +```py df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"]) df["grade"] @@ -1717,7 +1717,7 @@ df["grade"] Out[77]: -``` +```py 0 very good 1 good 2 good @@ -1732,14 +1732,14 @@ Categories (5, object): [very bad, bad, medium, good, very good] In [78]: -``` +```py df.groupby("grade").size() ``` Out[78]: -``` +```py grade very bad 1 bad 0 @@ -1755,7 +1755,7 @@ dtype: int64 In [79]: -``` +```py plt.style.use('ggplot') ``` @@ -1764,7 +1764,7 @@ plt.style.use('ggplot') In [80]: -``` +```py ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) p = ts.cumsum().plot() @@ -2069,7 +2069,7 @@ hIhSEuCFECJKSYAXQogoJQFeCCGilAR4IYSIUv8f8P777wHo2GwAAAAASUVORK5CYII= In [81]: -``` +```py df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=['A', 'B', 'C', 'D']) @@ -2698,7 +2698,7 @@ AGMIPwAY8wFNd7R2zEaFBAAAAABJRU5ErkJggg== In [82]: -``` +```py df.to_csv('foo.csv') ``` @@ -2707,7 +2707,7 @@ df.to_csv('foo.csv') In [83]: -``` +```py pd.read_csv('foo.csv').head() ``` @@ -2728,7 +2728,7 @@ Out[83]: In [84]: -``` +```py df.to_hdf("foo.h5", "df") ``` @@ -2737,7 +2737,7 @@ df.to_hdf("foo.h5", "df") In [85]: -``` +```py pd.read_hdf('foo.h5','df').head() ``` @@ -2758,7 +2758,7 @@ Out[85]: In [86]: -``` +```py df.to_excel('foo.xlsx', sheet_name='Sheet1') ``` @@ -2767,7 +2767,7 @@ df.to_excel('foo.xlsx', sheet_name='Sheet1') In [87]: -``` +```py pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']).head() ``` @@ -2786,7 +2786,7 @@ Out[87]: In [88]: -``` +```py import glob import os diff --git a/docs/da/152.md b/docs/da/152.md index 1f3ccfe76..609eb8526 100644 --- a/docs/da/152.md +++ b/docs/da/152.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np import pandas as pd @@ -12,7 +12,7 @@ import pandas as pd 作为一维结构,它的索引叫做 `index`,基本调用方法为 -``` +```py s = pd.Series(data, index=index) ``` @@ -30,7 +30,7 @@ s = pd.Series(data, index=index) In [2]: -``` +```py s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"]) s @@ -39,7 +39,7 @@ s Out[2]: -``` +```py a -0.032806 b 0.050207 c -1.909697 @@ -52,14 +52,14 @@ dtype: float64 In [3]: -``` +```py s.index ``` Out[3]: -``` +```py Index([u'a', u'b', u'c', u'd', u'e'], dtype='object') ``` @@ -67,14 +67,14 @@ Index([u'a', u'b', u'c', u'd', u'e'], dtype='object') In [4]: -``` +```py pd.Series(np.random.randn(5)) ``` Out[4]: -``` +```py 0 -0.376233 1 -0.474349 2 1.660590 @@ -89,7 +89,7 @@ dtype: float64 In [5]: -``` +```py d = {'a' : 0., 'b' : 1., 'c' : 2.} pd.Series(d) @@ -98,7 +98,7 @@ pd.Series(d) Out[5]: -``` +```py a 0 b 1 c 2 @@ -109,14 +109,14 @@ dtype: float64 In [6]: -``` +```py pd.Series(d, index=['b', 'd', 'a']) ``` Out[6]: -``` +```py b 1 d NaN a 0 @@ -129,14 +129,14 @@ dtype: float64 In [7]: -``` +```py pd.Series(5., index=['a', 'b', 'c', 'd', 'e']) ``` Out[7]: -``` +```py a 5 b 5 c 5 @@ -149,14 +149,14 @@ dtype: float64 In [8]: -``` +```py s ``` Out[8]: -``` +```py a -0.032806 b 0.050207 c -1.909697 @@ -169,14 +169,14 @@ dtype: float64 In [9]: -``` +```py s[0] ``` Out[9]: -``` +```py -0.032806330572971713 ``` @@ -184,14 +184,14 @@ Out[9]: In [10]: -``` +```py s[:3] ``` Out[10]: -``` +```py a -0.032806 b 0.050207 c -1.909697 @@ -202,14 +202,14 @@ dtype: float64 In [11]: -``` +```py s[s > s.median()] ``` Out[11]: -``` +```py a -0.032806 b 0.050207 dtype: float64 @@ -219,14 +219,14 @@ dtype: float64 In [12]: -``` +```py s[[4, 3, 1]] ``` Out[12]: -``` +```py e -0.073793 d -1.127865 b 0.050207 @@ -237,14 +237,14 @@ dtype: float64 In [13]: -``` +```py np.exp(s) ``` Out[13]: -``` +```py a 0.967726 b 1.051488 c 0.148125 @@ -259,14 +259,14 @@ dtype: float64 In [14]: -``` +```py s["a"] ``` Out[14]: -``` +```py -0.032806330572971713 ``` @@ -274,7 +274,7 @@ Out[14]: In [15]: -``` +```py s["e"] = 12. s @@ -283,7 +283,7 @@ s Out[15]: -``` +```py a -0.032806 b 0.050207 c -1.909697 @@ -296,27 +296,27 @@ dtype: float64 In [16]: -``` +```py "e" in s ``` Out[16]: -``` +```py True ``` In [17]: -``` +```py "f" in s ``` Out[17]: -``` +```py False ``` @@ -324,14 +324,14 @@ False In [18]: -``` +```py s.get("f", np.nan) ``` Out[18]: -``` +```py nan ``` @@ -341,14 +341,14 @@ nan In [19]: -``` +```py s + s ``` Out[19]: -``` +```py a -0.065613 b 0.100413 c -3.819395 @@ -359,14 +359,14 @@ dtype: float64 In [20]: -``` +```py s * 2 ``` Out[20]: -``` +```py a -0.065613 b 0.100413 c -3.819395 @@ -379,14 +379,14 @@ dtype: float64 In [21]: -``` +```py s[1:] + s[:-1] ``` Out[21]: -``` +```py a NaN b 0.100413 c -3.819395 @@ -403,7 +403,7 @@ dtype: float64 In [22]: -``` +```py s = pd.Series(np.random.randn(5), name='something') s.name @@ -411,6 +411,6 @@ s.name Out[22]: -``` +```py 'something' ``` \ No newline at end of file diff --git a/docs/da/153.md b/docs/da/153.md index eb63c9fe4..f29ea4def 100644 --- a/docs/da/153.md +++ b/docs/da/153.md @@ -2,7 +2,7 @@ In [1]: -``` +```py import numpy as np import pandas as pd @@ -26,7 +26,7 @@ import pandas as pd In [2]: -``` +```py d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} @@ -36,7 +36,7 @@ d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), In [3]: -``` +```py df = pd.DataFrame(d) df @@ -56,7 +56,7 @@ Out[3]: In [4]: -``` +```py pd.DataFrame(d, index=['d', 'b', 'a']) ``` @@ -73,7 +73,7 @@ Out[4]: In [5]: -``` +```py pd.DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three']) ``` @@ -90,27 +90,27 @@ Out[5]: In [6]: -``` +```py df.index ``` Out[6]: -``` +```py Index([u'a', u'b', u'c', u'd'], dtype='object') ``` In [7]: -``` +```py df.columns ``` Out[7]: -``` +```py Index([u'one', u'two'], dtype='object') ``` @@ -120,7 +120,7 @@ Index([u'one', u'two'], dtype='object') In [8]: -``` +```py d = {'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]} @@ -130,7 +130,7 @@ d = {'one' : [1., 2., 3., 4.], In [9]: -``` +```py pd.DataFrame(d) ``` @@ -148,7 +148,7 @@ Out[9]: In [10]: -``` +```py pd.DataFrame(d, index=['a', 'b', 'c', 'd']) ``` @@ -168,7 +168,7 @@ Out[10]: In [11]: -``` +```py data = np.zeros((2,), dtype=[('A', 'i4'),('B', 'f4'),('C', 'a10')]) data[:] = [(1,2.,'Hello'), (2,3.,"World")] @@ -178,7 +178,7 @@ data Out[11]: -``` +```py array([(1, 2.0, 'Hello'), (2, 3.0, 'World')], dtype=[('A', ' 2 @@ -363,7 +363,7 @@ Out[21]: In [22]: -``` +```py del df["two"] three = df.pop("three") @@ -385,7 +385,7 @@ Out[22]: In [23]: -``` +```py df['foo'] = 'bar' df @@ -405,7 +405,7 @@ Out[23]: In [24]: -``` +```py df['one_trunc'] = df['one'][:2] df @@ -427,7 +427,7 @@ Out[24]: In [25]: -``` +```py df.insert(1, 'bar', df['one']) df @@ -447,7 +447,7 @@ Out[25]: In [28]: -``` +```py df.assign(test=df["one"] + df["bar"]) ``` diff --git a/docs/da/README.md b/docs/da/README.md index 600f45333..7e356fcc3 100644 --- a/docs/da/README.md +++ b/docs/da/README.md @@ -23,7 +23,7 @@ 安装好 `Python` 和相应的包之后,可以在命令行下输入: -``` +```py $ ipython notebook ``` @@ -37,7 +37,7 @@ $ ipython notebook * 更新环境 - ``` + ```py conda update conda conda update anaconda ```