# Part 1: Introduction to Python
## 1.1 [About Python](https://lectures.quantecon.org/py/about_py.html#id3)
### 1.1.1 Overview
### 1.1.2 What's Python?
### 1.1.3 Scientific Programming
- [Machine learing and data science](http://scikit-learn.org/stable/)
- [Astronomy(天文学)](http://www.astropy.org/)
- [Artificial intelligence](https://wiki.python.org/moin/PythonForArtificialIntelligence)
- [Chemistry](http://chemlab.github.io/chemlab/)
- [Computational biology](http://biopython.org/)
- [Meteorology(气象学)](https://pypi.python.org/pypi/metrology)

### 1.1.4 Learn More
#### Numerical Programming


```python
import numpy as np                      # Load the library

a = np.linspace(-np.pi,np.pi,100)        # Create even grid from -pi to pi
b = np.cos(a)                            # Apply cosine to each element of a
c = np.sin(a)                            # Apply sin to each element of a
```


```python
np.dot(b,c)       # matrix multiplication
```




    -1.8041124150158794e-16




```python
b @ c            # matrix multiplication
# element-wise product: np.multiply(), 或 *
```




    -1.8041124150158794e-16



#### SciPy
The SciPy library is built on top of NumPy and provides additional functionality For example, let’s calculate $\int^2_{-2}{\phi(z)dz}$ where $\phi$ is the standard normal density


```python
from scipy.stats import norm              # Load norm (normal distribution)
from scipy.integrate import quad          # Load quad (caculating intergration)
theta = norm()                            # Theta follows normal distribution
value, error = quad(theta.pdf, -2, 2)     # Integrate using Gaussian quadrature  .pdf 概率密度函数 .cdf 累计密度函数 -2,2 积分上下限
value                                     # 返回value的值
```




    0.9544997361036417




```python
# 使用cdf手动方法计算
import scipy.stats                       # Load library    
value=1-2*scipy.stats.norm.cdf(-2,loc=0,scale=1)              #http://blog.csdn.net/claroja/article/details/72830515
value
```




    0.95449973610364158



SciPy includes many of the standard routines used in
- [linear algebra(线性代数)](https://docs.scipy.org/doc/scipy/reference/linalg.html)
- [integration(整合)](https://docs.scipy.org/doc/scipy/reference/integrate.html)
- [interpolation(插补)](https://docs.scipy.org/doc/scipy/reference/interpolate.html)
- [optimization](https://docs.scipy.org/doc/scipy/reference/optimize.html)
- [distributions and random number generation](https://docs.scipy.org/doc/scipy/reference/stats.html)
- [signal processing](https://docs.scipy.org/doc/scipy/reference/signal.html)
- [etc.](https://docs.scipy.org/doc/scipy/reference/index.html)

#### Graphics  
[Library Matplotlib](https://matplotlib.org/gallery.html)  
Other graphics libraries include
- [Plotly](https://plot.ly/python/)
- [Bokeh](http://bokeh.pydata.org/en/latest/)
- [VPython](http://www.vpython.org/)

#### Symbolic Algebra(符号代数)


```python
from sympy import Symbol
```

Symbolic Computing (符号计算)


```python
x, y = Symbol('x'), Symbol('y')    # Treat 'x' and 'y' as algebraic symbols（代数符号）
x + x + x + y
```




    3*x + y



Factor Analysis (因子分析)


```python
expression = (x + y)**2        # **  乘方
expression.expand()            # .expand 展开式
```




    x**2 + 2*x*y + y**2



Solving Polynomials


```python
from sympy import solve
solve(x**2 + x + 2)           # 解方程
```




    [-1/2 - sqrt(7)*I/2, -1/2 + sqrt(7)*I/2]




```python
solve(x**2 + 2*x + 1)
```




    [-1]



Calculating Limits, Derivatives and Integrals(极限，导数，积分)


```python
from sympy import limit, sin, diff          
limit(1 / x, x, 0)                          #  求1/x的极限，其中x趋向于0
```




    oo




```python
limit(sin(x) / x, x, 0)
```




    1




```python
diff(sin(x), x)                         #  求sin（x）对x的导数
```




    cos(x)



#### Statistics
Python’s data manipulation and statistics libraries have improved rapidly over the last few years
#### Pandas
How to generate random number
如何生成随机数？ 
- numpy.random.uniform(low=0.0, high=1.0, size=None)  [0,1)均匀分布
- numpy.random.random(size=None) 
  - numpy.random.random((2, 3))   元组形式指定
- numpy.random.normal(size,loc,scale): 给出均值为loc，标准差为scale的高斯随机数
- numpy.random.rand(d0, d1, ..., dn)   [0,1)    标准正态分布
  numpy.random.randn(d0, d1, ..., dn)  没有限制   标准正态分布
  - 当函数括号内没有参数时，则返回一个浮点数
  - 当函数括号内有一个参数时，则返回秩为1的数组，不能表示向量和矩阵
  - 当函数括号内有两个及以上参数时，则返回对应维度的数组，能表示向量或矩阵
  - numpy.random.standard_normal() 函数与np.random.randn()类似，但是np.random.standard_normal() 的输入参数为元组（tuple）
- numpy.random.randint(low, high=None, size=None, dtype=’l’) 整数型



```python
np.random.uniform()
```




    0.8474738087470629




```python
np.random.uniform(2,3,6)              # [2,3)中均匀分布中的6个随机数
```




    array([ 2.9860889 ,  2.19519615,  2.00777363,  2.23653008,  2.05505467,
            2.89117726])




```python
np.random.uniform(2,3,(2,2))   
```




    array([[ 2.53819935,  2.85976506],
           [ 2.91869204,  2.64991819]])




```python
np.random.random()
```




    0.7304829610087114




```python
np.random.random(10)
```




    array([ 0.86273288,  0.5279635 ,  0.33135421,  0.72708269,  0.86928968,
            0.47071769,  0.05077265,  0.69756921,  0.16713672,  0.54353137])




```python
np.random.random((3,4))
```




    array([[ 0.96642415,  0.37624851,  0.32901655,  0.58515682],
           [ 0.62271202,  0.56993156,  0.47964188,  0.42931829],
           [ 0.60408005,  0.77272266,  0.00162158,  0.52869527]])




```python
np.random.normal(1,0.5,10)
```




    array([ 1.20349355,  1.17745893,  0.98227701,  1.58086968,  1.54173165,
            1.01738413,  0.91850826,  1.16709306,  1.03949584,  1.00972302])




```python
np.mean(np.random.normal(1,0.5,1000))
```




    0.97477448694503321




```python
np.random.normal(5,0.8,(2,4))
```




    array([[ 5.37148902,  5.52165235,  3.10762657,  3.21051536],
           [ 6.40331996,  5.35974761,  5.53317151,  4.81759955]])




```python
np.random.rand()
```




    0.6991420637529272




```python
np.random.rand(3)
```




    array([ 0.59372934,  0.2606707 ,  0.85677761])




```python
np.random.rand(2,2)
```




    array([[ 0.12969677,  0.26830264],
           [ 0.26575202,  0.15031921]])




```python
np.random.rand(3,2,2)           # 3组 2*2
```




    array([[[ 0.04667944,  0.56022617],
            [ 0.99076839,  0.2932098 ]],
    
           [[ 0.70883542,  0.72276065],
            [ 0.0241512 ,  0.66399433]],
    
           [[ 0.56175472,  0.93324534],
            [ 0.47822311,  0.29943678]]])




```python
np.random.rand(2,4,3,3)                    #  4 组 3*3 ， 这样的4组有2个
```




    array([[[[ 0.91655043,  0.12037943,  0.85462637],
             [ 0.31528861,  0.59644266,  0.24527812],
             [ 0.41429085,  0.80717022,  0.21825278]],
    
            [[ 0.89791812,  0.19810456,  0.75128835],
             [ 0.34516507,  0.8161068 ,  0.6074346 ],
             [ 0.19217673,  0.46841586,  0.22780444]],
    
            [[ 0.0995358 ,  0.38507414,  0.13525457],
             [ 0.71547676,  0.58165184,  0.54236188],
             [ 0.94241399,  0.42352624,  0.52700985]],
    
            [[ 0.55401586,  0.97291657,  0.26568722],
             [ 0.94813474,  0.69113245,  0.87098301],
             [ 0.58442572,  0.24803309,  0.18808223]]],
    
    
           [[[ 0.82405861,  0.06174618,  0.44058703],
             [ 0.04691451,  0.01917401,  0.97859124],
             [ 0.95750291,  0.38926466,  0.18569959]],
    
            [[ 0.19203849,  0.44958773,  0.61960534],
             [ 0.43102461,  0.79000366,  0.43515503],
             [ 0.16416595,  0.6032064 ,  0.1556198 ]],
    
            [[ 0.62336311,  0.26819523,  0.01729941],
             [ 0.01069535,  0.69215579,  0.03171449],
             [ 0.6912115 ,  0.17182265,  0.24050492]],
    
            [[ 0.59704035,  0.48744065,  0.74663878],
             [ 0.85071639,  0.89530915,  0.23641053],
             [ 0.3558962 ,  0.63559743,  0.79752732]]]])




```python
np.random.randn(2,2,3)
```




    array([[[ 0.41860832,  0.20000057,  1.61377788],
            [ 0.34181873, -1.41733621,  0.31367332]],
    
           [[-2.18577938,  0.47208238,  1.08411372],
            [ 0.56983538, -1.25560168, -1.44829982]]])




```python
np.random.standard_normal((2,2,3))
```




    array([[[ 0.33496069,  0.15313107,  0.68528172],
            [ 0.20353637, -0.06418014, -0.2242228 ]],
    
           [[ 0.01099221,  0.10426834, -0.51487265],
            [ 1.17121491, -0.55703709, -0.22933557]]])




```python
np.random.randint(5,7,(2,2,3))            # [5,7）  结构 （2,2,3）
```




    array([[[6, 6, 6],
            [5, 5, 5]],
    
           [[5, 6, 6],
            [6, 5, 6]]])




```python
import pandas as pd
np.random.seed(1234)                                                 #  在随机数中从1234这个位置开始抽取随机数

data = np.random.randn(5,2)                                          #  5x2 matrix of N(0, 1) random draws
dates = pd.date_range('01/03/2018', periods = 5)                     #  生成5期data，从2018/03/01开始

df = pd.DataFrame(data, columns = ('price', 'weight'), index = dates)  # 数据框格式，（数据，列名，编号为dates）
print(df)
```

                   price    weight
    2018-01-03  0.471435 -1.190976
    2018-01-04  1.432707 -0.312652
    2018-01-05 -0.720589  0.887163
    2018-01-06  0.859588 -0.636524
    2018-01-07  0.015696 -2.242685



```python
df.mean()                # 均值
```




    price     0.411768
    weight   -0.699135
    dtype: float64



#### Other Useful Statistics Libraries
- [statsmodels](http://www.statsmodels.org/stable/index.html)— various statistical routines 
- [scikit-learn](http://scikit-learn.org/stable/) —(machine learning in Python (sponsored by Google, among others) 
- [pyMC](http://pymc-devs.github.io/pymc/)—for Bayesian data analysis 
- [pystan](https://pystan.readthedocs.io/en/latest/) Bayesian analysis based on [stan](http://mc-stan.org/)   

#### Networks and Graphs
Library [NetworkX](http://networkx.github.io/)  
A simple netword sample


```python
import networkx as nx                              #  network library
import matplotlib.pyplot as plt                    #  plot library
import numpy as np
np.random.seed(1234)                               # seef of random number

# Generate random graph
# function: numpy.random.uniform(low,high,size)
p = dict((i,(np.random.uniform(0,1),np.random.uniform(0,1))) for i in range(200))     
# dict: dictionary
# genenrate {0:(0.5,0.8), 1:(0.6,0.7), 2:(0.2,0.9),.....,199:(0.3,0.8)}
G = nx.random_geometric_graph(200, 0.12, pos = p)
# position is stored as node attribute data for random_geometric_graph
# <networkx.classes.graph.Graph at 0xc03c588>
pos = nx.get_node_attributes(G, 'pos')
#  Get node attributes from graph
```

`nx.random_geometric_graph(n, radius, dim=2, pos=None)`  
-   `n` : int;              Number of nodes  
-   `radius`: float ;         Distance threshold value  
-   `dim` : int, optional;      Dimension of graph  
-   `pos` : dict, optional ;    A dictionary keyed by node with node positions as values.  

` nx.get_node_attributes(G, name)`    
-   `G` :            NetworkX Graph  
-   `name` : string ;    Attribute name


```python
# find node nearest the center point (0.5, 0.5)
# 离中心越远，颜色变化的设定？
dists = [(x - 0.5)**2 + (y - 0.5)**2 for x,y in list(pos.values())]
# dists = [(x - 0.2)**2 + (y - 0.8)**2 for x,y in list(pos.values())]
ncenter = np.argmin(dists)               # argmin()  求出离中心最近的那个点，命名为C点

```


```python
# Plot graph, coloring by path length from central node
p = nx.single_source_shortest_path_length(G, ncenter)    # 计算C点离其他点的距离
plt.figure()                                             # 设置一副空图
nx.draw_networkx_edges(G, pos, alpha=0.5)                # 画出线条  alpha：边缘透明度
nx.draw_networkx_nodes(G,                                # 画出点
                      pos,                               # 点的属性
                      nodelist=list(p.keys()),           # Draw only specified nodes (default G.nodes())
                      node_size=120,alpha=0.5,
                      node_color=list(p.values()),
                      cmap=plt.cm.jet_r)                # Colormap for mapping intensities of nodes (default=None)
plt.show()
```

#### Cloud Computing
Library: [Wakar](https://www.wakari.io/)
See also 
- [Amazon Elastic Compute Cloud](http://aws.amazon.com/ec2/)
- [The Google App Engine (Python, Java, PHP or Go)](https://cloud.google.com/appengine/)
- [Pythonanywhere](https://www.pythonanywhere.com/)
- [Sagemath Cloud](https://cloud.sagemath.com/)

#### Parallel Processing
- [Parallel computing through IPython clusters](http://ipython.org/ipython-doc/stable/parallel/parallel_demos.html)
- [The Starcluster interface to Amazon’s EC2](http://star.mit.edu/cluster/)
- GPU programming through [PyCuda](https://wiki.tiker.net/PyCuda), [PyOpenCL](https://mathema.tician.de/software/pyopencl/), [Theano](http://deeplearning.net/software/theano/) or similar   

#### Other Developments
- [Jupyter](http://jupyter.org/)—Python in your browser with code cells, embedded images, etc.
- [Numba](http://numba.pydata.org/) —Make Python run at the same speed as native machine code! 
- [Blaze](http://blaze.pydata.org/) —a generalization of NumPy 
- [PyTables](http://www.pytables.org/)— manage large data sets 
- [CVXPY](https://github.com/cvxgrp/cvxpy) — convex optimization in Python 

## 1.2 [Setting up Your Python Environment](https://lectures.quantecon.org/py/getting_started.html)
### 1.2.1 Overview
### 1.2.2 First Steps Anaconda
### 1.2.3 Jupyter
#### A Test Program  
Don’t worry about the details for now — let’s just run it and see what happens


```python
import numpy as np
import matplotlib.pyplot as plt

N = 20                                                    
theta = np.linspace(0.0, 2 * np.pi, N, endpoint = False)   # [0,2pi] 中生成20个节点
radii = 10 * np.random.rand(N)                             # 生成[0,9]随机数
width = np.pi / 4 * np.random.rand(N)                      # 
ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=0.0)

# Use custom colors and opacity
for r, bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.jet(r / 10.))
    bar.set_alpha(0.5)
plt.show()
```


```python
np.random?
```

`np.  `
安住 tab 选择属性

### 1.2.4 Additional Software
#### Installing QuantEcon.py
control+r  
cmd  
`
pip install quantecon
`
#### Method 1: Copy and Paste
#### Method 2: Run
- pwd asks Jupyter to show the PWD (or %pwd — see the comment about automagic above)
  – This is where Jupyter is going to look for files to run  
  – Your output will look a bit different depending on your OS
- ls asks Jupyter to list files in the PWD (or %ls)  
  – Note that test.py is there (on our computer, because we saved it there earlier)
- cat test.py asks Jupyter to print the contents of test.py (or !type test.py onWindows)
- run test.py runs the file and prints any output

### 1.2.5 Alternatives
ipython blah blah

### 1.2.6 Exercises

## [1.3 An Introductory Example](https://lectures.quantecon.org/py/python_by_example.html)

### 1.3.1 Overview

### 1.3.2 The Task: Plotting a White Noise Process

### 1.3.3 Version 1



```python
import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(100)    # 100个随机数
plt.plot(x)                 # 画出x
plt.show()                  # 呈现出来
```


```python
import numpy as np
np.sqrt(4)               # 开根号
```




    2.0




```python
import numpy
numpy.sqrt(4)
```




    2.0




```python
from numpy import sqrt
sqrt(4)
```




    2.0



### 1.3.4 Alternative Versions
#### A Version with a For Loop


```python
import numpy as np
import matplotlib.pyplot as plt

ts_length = 100               
_values = []                 # 设置一个空的列表，之后才能往里面加东西呀 
 
for i in range(ts_length):   # 循环 ts_length = 100  次
    e = np.random.randn()    # 每次循环跳出一个随机数
    _values.append(e)        # 将这个随机数加到已经定义的列表中

plt.plot(_values, 'b-')     #'b-':line type ，the color is blue
#plt.plot(_values, 'r-')    # 试试看这种颜色好了
plt.show()
```

#### Lists
- 列表用[]框起来
- 元组用()框起来


```python
x = [10, 'foo', False]     # We can include heterogeneous data inside a list 不同类型的都放一起，数值型、字符型、布尔型（就是逻辑型啦）
type(x)                    # 看看x是什么类型的
```




    list




```python
x                         # 告诉我x里面都是什么呢？
```




    [10, 'foo', False]




```python
x.append(2.5)            # 我想再加一点东西
x                        # 在告诉我现在x变什么样了
```




    [10, 'foo', False, 2.5]




```python
x.pop()                 # 我想删了最后一个元素
```




    2.5




```python
x                      # again
```




    [10, 'foo', False]




```python
x[0]                # 看看x的第一个数是什么，[]里面是元素的位置，记住是从0开始哟
```




    10




```python
x[1]               # 第二个元素是什么呢
```




    'foo'



#### The For Loop    循环


```python
for i in range(ts_length):      # 这个上面见过咯
    e = np.random.randn()
    _values.append(e)
```


```python
animals = ['dog', 'cat', 'bird']
for animal in animals:                      # 前面的animal 可以写成i ,a,b 啥都行
    print("The plural of " + animal + " is " + animal + "s")      
    #  我想写成 The plural of 填充 is 填充s。 
    # 字符型 加上双引号，空格也要加上，用 + 连接
    # 有三个元素就循环三次
```

    The plural of dog is dogs
    The plural of cat is cats
    The plural of bird is birds


`
for variable_name in sequence:  
    <code block>
`   
#### Code Blocks and Indentation
三种循环形式  
`
for i in range(10):
if x > y:
while x < 100:
etc., etc.
`

#### While Loops


```python
import numpy as np
import matplotlib.pyplot as plt

ts_length = 100
_values = []
i = 0
while i < ts_length:                # 当且仅当 i比100小的时候循环
    e = np.random.randn() 
    _values.append(e)
    i = i + 1                       # 每次循环i都要增加1，一直增加到99，再加1变成100的时候就不能进入循环了，所以循环的i为0~99,100次
plt.plot(_values, 'b-')
plt.show()
```

#### User-Defined Functions
用定义函数的形式进行循环


```python
import numpy as np
import matplotlib.pyplot as plt

def generation_data(n):                    #  定义 一个函数，以后输入genenration_data(n)就能生成n个随机数了。
    _values =[]                            #  定义一个空列表
    for i in range(n):                     #  循环
        e = np.random.randn()
        _values.append(e)
    return _values                         # 通过这个函数可以得到100个随机数，都在_values列表里面
data = generation_data(100)                # 有了这个函数，先生成100个数
plt.plot(data,'b-')                        # 画图
plt.show()
        
```

#### Conditions
给定义的函数多添加点属性吧


```python
import numpy as np
import matplotlib.pyplot as plt

def generate_data(n, generator_type):           # 定义一个可以生成n个随机数同时带有两种属性的函数
    _values = []
    for i in range(n):
        if generator_type == 'U':               # 其中一种属性就叫 U 好了
            e = np.random.uniform(0,1)          # U这种属性呢，会提供[0,1）均匀分布的随机数
        else:
            e = np.random.randn()               # 如果用户没有输入他想要的属性，那就默认给他（0,1）正态分布的随机数吧
        _values.append(e)                       # 任一情况生成的随机数都放到列表里，注意要和if对齐，因为它不属于if else内部。
    return _values                              # 循环完成，得到了完整的列表了，要与for对齐，他是循环的总结果嘛

data = generate_data(100, 'U')                  # 现在来100个均匀分布的随机数吧
plt.plot(data, 'b-')
plt.show()
```


```python
import numpy as np
import matplotlib.pyplot as plt

def generate_data(n, generator_type):
    _values = []
    for i in range(n):
        e = generator_type()            
        # 允许多种选择了，但是用户要回写随机数代码
        # 输入np.random.uniform,这一行就变成 e = np.random.uniform(),跟上面完全一样啊
        # 输入np.random.rand,这一行就变成 e = np.random.rand()
        # 就是最简单的替换啊
        _values.append(e)
    return _values

data = generate_data(100, np.random.uniform)
plt.plot(data, 'b-')
plt.show()
    
```


```python
max(7, 2, 4)           # 最大值
```




    7




```python
m = max
m(7, 2, 4)              # 这不也是简单替换吗
```




    7



#### List Comprehensions


```python
animals = ['dog', 'cat', 'bird']
plurals = [animal + 's' for animal in animals]            # for in 简单的循环
plurals
```




    ['dogs', 'cats', 'birds']




```python
range(8)             # range(8)是，[0, 1, 2, 3, 4, 5, 6, 7]     range(0, 8) 是[0,8)
```




    range(0, 8)




```python
[x for x in range(8)]
```




    [0, 1, 2, 3, 4, 5, 6, 7]




```python
doubles = [2 * x for x in range(8)]
doubles
```




    [0, 2, 4, 6, 8, 10, 12, 14]



将  
`
_values = []  
for i in range(n):  
    e = generator_type()  
    _values.append(e)    
`  
简化为  
`
_values = [generator_type() for i in range(n)]  
`

### 1.3.5 Exercises
#### Exercise 1
n!


```python
import numpy as np
import matplotlib.pyplot as plt

def factorial(n):                 # 定义这个函数 factorial(n)
    e = 2
    _values = 1
    while e < n + 1:             # 因为 n 也要乘进去，所以 要循环到 < n+1    # 第二次循环e = 3进来了        # e = n< n +1可以进来
        _values = _values * e    # 第一次 1*2                                # 第二次1*2的上一次结果再*3    #  （n-1）！* n 得到 n！了
        e = e + 1                # 第一次 3                                  # e = 4 。。。。               # e = n+1  退出循环
    return _values
factorial(10)
```




    3628800




```python
def factorial(n):               # 书上写的很简单啊
    k = 1
    for i in range(n):
        k = k * (i + 1)
    return k
factorial(10)
```




    3628800



#### Exercise 2
binomial random variable Y ~ Bin(n, p)
均匀分布，n个随机数小于P的个数


```python
from numpy.random import uniform
def binomial_rv(n, p):
    count = 0
    for i in range(n):
        U = uniform(0,1)
        if U < p:
            count = count + 1
    return count
binomial_rv(10,0.5)
```




    7



#### Exercise 3
Compute an approximation to $\pi$ using Monte Carlo.
计算pi的值  
设想往1\*1的方格随机丢种子，种子在半径为0.5的圆中的概率是 pi\*0.5\*\*2，嗯，这样算出概率然后在乘上1/(0.5\*\*2)=4,就能算出pi值了。


```python
import numpy as np
n = 100000
count = 0
for i in range(n):
    x = np.random.uniform()
    y = np.random.uniform()
    r = np.sqrt((x - 0.5)**2 + (y - 0.5)**2) 
    if r < 0.5:
        count += 1
count*4/n
```




    3.13956



#### Exercise 4
均匀分布，连续三次大于0.5，就支付一美元


```python
from numpy.random import uniform
_values = []
for i in range(10):
    a = uniform()
    if a >= 0.5:
        b = 1
    else:
        b = 0
    _values.append(b)
_values
```




    [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]




```python
count = 0
for i in range(0,9):
    if _values[i:i+3] == [1,1,1]:
        count = count + 1
if count>=1:
    print('pay one dollar')
```

    pay one dollar



```python
from numpy.random import uniform
payoff = 0
count = 0
for i in range(10):
    U = uniform()
    count = count + 1 if U < 0.5 else 0               #在U<0.5时+1，>=0.5时+0
    if count == 3:
        payoff = 1
print(payoff)
```

    1


#### Exercise 5
Time series  
$x_t = 0.9 * x_{t-1}+\epsilon$ 画出两百期的时间序列


```python
import numpy as np
import matplotlib.pyplot as plt
alpha = 0.9
ts_length = 200
current_x = 0

x_values = []
for i in range(ts_length + 1):    #[0,200] 201个数
    x_values.append(current_x)
    current_x = alpha * current_x + np.random.randn()     # current_x 不断进入
plt.plot(x_values, 'b-')
plt.show()
```

#### Exercise 6


```python
import numpy as np
import matplotlib.pyplot as plt
x = [np.random.randn() for i in range(100)]
plt.plot(x, 'b-', label="white noise")        # 添加一个标签
plt.legend()                                  # 要写这句话，标签才能显示出来
plt.show()
```


```python
import numpy as np
import matplotlib.pyplot as plt
for alpha in [0,0.8,0.98]:             # 三个不同的系数循环
    ts_length = 200
    current_x = 0
    x_values = []
    for i in range(ts_length + 1):    #[0,200] 201个数   循环内套循环
        x_values.append(current_x)
        current_x = alpha * current_x + np.random.randn()
    plt.plot(x_values, label=r'$\alpha =$ ' + str(alpha))    # ''前面要加 r     $数学公式$   
plt.legend()
plt.show()

```


```python
alphas = [0.0, 0.8, 0.98]
ts_length = 200
for alpha in alphas:                # 先有循环的列表，再循环
    x_values = []
    current_x = 0
    for i in range(ts_length):
        x_values.append(current_x)
        current_x = alpha * current_x + np.random.randn()
    plt.plot(x_values, label=r'$\alpha$ = ' + str(alpha))
plt.legend()
plt.show()
```

## 1.4 [Python Essentials](https://lectures.quantecon.org/py/python_essentials.html)
### 1.4.1 Overview
### 1.4.2 Data Types
#### Primitive Data Types
布尔型


```python
x = True
y = 100 < 10 # Python evaluates expression on right and assigns it to y
y
```




    False




```python
type(y)
```




    bool




```python
x + y         # True 为1， False 为0
```




    1




```python
x * y
```




    0




```python
True + True
```




    2




```python
bools = [True, True, False, True]  # List of Boolean values
sum(bools)
```




    3




```python
a, b = 1, 2                # 整数型
c, d = 2.5, 10.0           # 浮点型
type(a)
```




    int




```python
type(c)
```




    float




```python
1 / 2
```




    0.5




```python
1 // 2                 #  取 整
```




    0




```python
x = complex(1, 2)      # 复数计算
y = complex(2, 1)
x * y
```




    5j



#### Containers 容器


```python
x = ('a', 'b')  # Round brackets instead of the square brackets
x = 'a', 'b'   # Or no brackets at all---the meaning is identical
x
```




    ('a', 'b')




```python
type(x)         # 数组
```




    tuple




```python
x = [1, 2]   # List
x[0] = 10    # Now x = [10, 2]      第一个数被10替代了
```


```python
x = (1, 2)   # tuple cant be changed  元组是不能被替换的
x[0] = 10    
```


```python
integers = (10, 20, 30)
x, y, z = integers
x
```




    10




```python
y
```




    20



#### Slice Notation  切片


```python
a = [2, 4, 6, 8] 
a[1:]              # 从第2位往后
```




    [4, 6, 8]




```python
a[1:3]            # 从第2位到第3位    [1,3)
```




    [4, 6]




```python
a[-2:]            # 倒数第2位到最后
```




    [6, 8]




```python
s = 'foobar'
s[-3:] # Select the last three elements
```




    'bar'



#### Sets and Dictionaries  集与字典


```python
d = {'name': 'Frodo', 'age': 33}      # 一一对应
type(d)
```




    dict




```python
d['age']               
```




    33




```python
s1 = {'a', 'b'}
type(s1)
```




    set




```python
s2 = {'b', 'c'}            
s1.issubset(s2)              # s1 是 s2 子集吗   X
```




    False




```python
s1.intersection(s2)         # 交集
```




    {'b'}




```python
s3 = set(('foo', 'bar', 'foo'))   # Unique elements only
s3
```




    {'bar', 'foo'}



### 1.4.3 Imports


```python
import math
math.sqrt(4)
```




    2.0




```python
from math import *
sqrt(4)
```




    2.0



### 1.4.4 Input and Output


```python
f = open('newfile.txt', 'w') # Open 'newfile.txt' for writing
f.write('Testing\n')        # Here '\n' means new line 写入
f.write('Testing again')    # 写入
f.close()                   # 关闭
```


```python
%pwd                       # 文件位置
```




    'C:\\Users\\Administrator\\Desktop\\QuantEcon'




```python
f = open('newfile.txt', 'r')    # 打开，读入
out = f.read()                  # 读入
out
```




    'Testing\nTesting again'




```python
print(out)
```

    Testing
    Testing again



```python
f = open('C:\\Users\\Administrator\\Desktop\\QuantEcon\\newfile.txt', 'r')
```

### 1.4.5 Iterating
#### Looping over Different Objects
让我们写一个us_cities.txt文件，列出美国的城市和他们的人口


```python
%%file us_cities.txt        
new york: 8244910
los angeles: 3819702
chicago: 2707120
houston: 2145146
philadelphia: 1536471
phoenix: 1469471
san antonio: 1359758
san diego: 1326179
dallas: 1223229
```

    Overwriting us_cities.txt



```python
data_file = open('us_cities.txt', 'r')
for line in data_file:
    city,population = line.split(':')             # Tuple unpacking    根据‘：’将他们分割开来
    city = city.title()                           # Capitalize city names   城市名称大写
    population = '{0:,}'.format(int(population))  # Add commas to numbers   数字添加，
    print(city.ljust(15) + population)            # ljust是python中用于将字符串填充至指定长度的内置函数
data_file.close()
```

    New York       8,244,910
    Los Angeles    3,819,702
    Chicago        2,707,120
    Houston        2,145,146
    Philadelphia   1,536,471
    Phoenix        1,469,471
    San Antonio    1,359,758
    San Diego      1,326,179
    Dallas         1,223,229


#### Looping without Indices


```python
x_values = [1,2,3]       #Some iterable x    
for x in x_values:
    print(x * x)
```

    1
    4
    9



```python
for i in range(len(x_values)):
    print(x_values[i] * x_values[i])
```

    1
    4
    9



```python
# Python提供了一些工具来简化没有索引的循环
# 一个是zip()，它用于从两个序列中逐个进行配对
countries = ('Japan', 'Korea', 'China')
cities = ('Tokyo', 'Seoul', 'Beijing')
for country, city in zip(countries, cities):
    print('The capital of {0} is {1}'.format(country, city))        # {0}和{1}是（country，city）列表的位置 
```

    The capital of Japan is Tokyo
    The capital of Korea is Seoul
    The capital of China is Beijing



```python
names = ['Tom', 'John']
marks = ['E', 'F']
dict(zip(names, marks))
```




    {'John': 'F', 'Tom': 'E'}



If we actually need the index from a list, one option is to use enumerate()


```python
letter_list = ['a', 'b', 'c']
for index, letter in enumerate(letter_list):
    print("letter_list[{0}] = '{1}'".format(index, letter))      # {0}和{1}是（index， letter）列表的位置
```

    letter_list[0] = 'a'
    letter_list[1] = 'b'
    letter_list[2] = 'c'


### 1.4.6 Comparisons and Logical Operators
#### Comparisons


```python
x, y = 1, 2
x < y
```




    True




```python
x > y
```




    False




```python
1 < 2 < 3
```




    True




```python
1 <= 2 <= 3
```




    True




```python
x = 1      # Assignment
x == 2     # Comparison
```




    False




```python
1 != 2
```




    True




```python
x = 'yes' if 42 else 'no'           # 其他值就是True
x
```




    'yes'




```python
x = 'yes' if [] else 'no'           # []和()相当于False
x
```




    'no'



The rule is:  
- Expressions that evaluate to zero, empty sequences or containers (strings, lists, etc.) and None are all equivalent to False  
  – for example, [] and () are equivalent to False in an if clause  
- All other values are equivalent to True  
  – for example, 42 is equivalent to True in an if clause
  
#### Combining Expressions


```python
1 < 2 and 'f' in 'foo'        # 两个都是对的
```




    True




```python
1 < 2 and 'g' in 'foo'        # 其中一个是错的
```




    False




```python
1 < 2 or 'g' in 'foo'         # x 或 y 
```




    True




```python
not True
```




    False




```python
not not True
```




    True



Remember
- P and Q is True if both are True, else False
- P or Q is False if both are False, else True

### 1.4.7 More Functions


```python
max(19, 20)
```




    20




```python
range(4) # in python3 this returns a range iterator object
```




    range(0, 4)




```python
list(range(4)) # will evaluate the range iterator and create a list
```




    [0, 1, 2, 3]




```python
str(22)                   # 数值型转字符型
```




    '22'




```python
type(22)                 # 22的类型是整数型
```




    int




```python
bools = False, True, True
all(bools) # True if all are True and False otherwise
```




    False




```python
any(bools) # False if all are False and True otherwise
```




    True



#### The Flexibility of Python Functions 


```python
def f(x):
    if x < 0:                    #  定义一个函数， 如果x<0，则返回negetive，其他情况返回nonnegative
        return 'negative'
    return 'nonnegative'
```


```python
# Filename: temp.py
def f(x):
    """
    This function squares its argument
    """
    return x**2             #  f(x) = x**2
```


```python
f(50)
```




    2500



#### One-Line Functions: lambda


```python
def f(x):
    return x**3
```


```python
f = lambda x: x**3             # 简化定义函数方法
```

calculating $\int_0^2{x^3dx}$  
The syntax of the quad function is `quad(f, a, b)` where f is a function and a and b are numbers


```python
from scipy.integrate import quad          # 计算积分
quad(lambda x:x**3, 0, 2)
```




    (4.0, 4.440892098500626e-14)



#### Keyword Arguments


```python
def f(x, coefficients=(1, 1)):
    a, b = coefficients
    return a + b * x
```


```python
f(2, coefficients=(0, 0))       # 0+0*2
```




    0




```python
f(2)  # Use default values (1, 1)
```




    3



### 1.4.8 Coding Style and PEP8

### 1.4.9 Exercises
#### Exercise 1
对应元素相乘


```python
x_vals = [1, 2, 3]                    
y_vals = [1, 1, 1]
sum([x * y for x, y in zip(x_vals, y_vals)])
```




    6



0-99中偶数数量


```python
3 % 2 == 0
```




    False




```python
sum([x % 2 == 0 for x in range(100)])   # x % 2余数为0 为偶数，返回True，也就是1
```




    50



（x，y）同时为偶数的次数


```python
pairs = ((2, 5), (4, 2), (9, 8), (12, 10))
sum([x % 2 == 0 and y % 2 == 0 for x, y in pairs])
```




    2



#### Exercise 2  
计算 $ p(x)= a_0+a_1x+a_2x^2+a_3x^3+a_4x^4+...+a_nx^n$


```python
def p(x, coeff):
    return sum(a * x**i for i, a in enumerate(coeff)) # 指代coeff中数值的位置，a是coeff中的数值
```


```python
p(1,[1,2])
```




    3



#### Exercise 3
判断字符串中大写字母个数


```python
def f(string):
    count = 0
    for letter in string:
        if letter == letter.upper() and letter.isalpha():  # isalpha 判断是否是英文字母 如果这个字母是大写就进入循环
            count +=1
    return count
f('L`Arc En Ciel')
```




    4



#### Exercise 4
字符串A是否是字符串B的子集


```python
def f(seq_a, seq_b):
    is_subset = True            # 定义函数 先假设 a是b的子集 
    for a in seq_a:
        if a not in seq_b:      # 如果不是子集的话
            is_subset = False   # 修正之前的假设
    return is_subset            # 返回
# == test == #
print(f([1, 2], [1, 2, 3]))
print(f([1, 2, 3], [1, 2]))
print(f("L`Arc En Ciel","L`Arc En Ciel X"))
```

    True
    False
    True



```python
def f(seq_a, seq_b):
    return set(seq_a).issubset(set(seq_b))   # 超简化写法
```

#### Exercise 5
近似算x点函数值  
将[a,b]区间用n个节点等分


```python
def linapprox(f, a, b, n, x):

   # Evaluates the piecewise linear interpolant of f at x on the interval [a, b], with n evenly spaced grid points.
   # Parameters
   # ==========
   #     f : function
   #         The function to approximate
   #     x, a, b : scalars (floats or integers)
   #         Evaluation point and endpoints, with a <= x <= b
   #     n : integer
   #         Number of grid points
   # Returns
   # ========= 
   #     A float. The interpolant evaluated at x
   
    length_of_interval = b - a     #  区间长度
    num_subintervals = n - 1       # 分成n-1份
    step = length_of_interval / num_subintervals   # 步长

    # === find first grid point larger than x === #
    point = a                     
    while point <= x:              # 求得大于x，且离x最近的节点
        point += step              # point = point + step
    # === x must lie between the gridpoints (point - step) and point === #
    # x 一定在（point-step，point）间
    u, v = point - step, point
    return f(u) + (x - u) * (f(v) - f(u)) / (v - u)


```

be691cde8a44424fb422b4029a3053095362b43d
ipynb
Jupyter Notebook
1.1-1.4 Introduction to Python.ipynb
gurusmile/QuantEcon
d905f077af93e104424dce9ac449b8f966175080
MIT
1.1-1.4 Introduction to Python.ipynb
gurusmile/QuantEcon
d905f077af93e104424dce9ac449b8f966175080
MIT
1.1-1.4 Introduction to Python.ipynb
gurusmile/QuantEcon
d905f077af93e104424dce9ac449b8f966175080
MIT
Qwen/Qwen-72B
1. YES
2. YES