# Plot multi-tree model views

To demonstrate how the multi-tree models work, this notebook shows example views of a tree from an origin timepoint and subsequent subtrees added at later timepoints. These views should clarify the following points:

  - topological variation between timepoints
  - width of training and validation time windows
  - clade assignments by timepoint
  - clade linkage between timepoints by traversal

## Imports

```python
from augur.titer_model import TiterCollection
from augur.utils import json_to_tree
import json
import matplotlib as mpl
from matplotlib import gridspec
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np
import pandas as pd
import seaborn as sns

%matplotlib inline
```

```python
sns.set_style("ticks")
plt.style.use("huddlej")
```

```python
mpl.rcParams['savefig.dpi'] = 120
mpl.rcParams['figure.dpi'] = 120
mpl.rcParams['font.weight'] = 300
mpl.rcParams['axes.labelweight'] = 300
mpl.rcParams['font.size'] = 14
```

```python
tip_size = 14
```

```python
end_date = 2003.0
```

## Load trees

```python
with open("../results/auspice/flu_h3n2_10_sample_0_1994-10-01_2015-10-01_2001-10-01_ha_tree.json", "r") as fh:
    origin_tree_json = json.load(fh)
```

```python
origin_tree = json_to_tree(origin_tree_json)
```

```python
with open("../results/auspice/flu_h3n2_10_sample_0_1994-10-01_2015-10-01_2002-10-01_ha_tree.json", "r") as fh:
    next_tree_json = json.load(fh)
```

```python
next_tree = json_to_tree(next_tree_json)
```

## Plot origin tree

```python
def plot_tree(tree, color_by_trait=None, initial_branch_width=5, tip_size=10,
              start_date=None, end_date=None, include_color_bar=False, ax=None, colorbar_ax=None,
              earliest_node_date=None, default_color="#cccccc", override_y_values=None,
              cmap=None):
    """Plot a BioPython Phylo tree in the BALTIC-style.
    """
    # Plot H3N2 tree in BALTIC style from Bio.Phylo tree.
    if override_y_values is None:
        override_y_values = {}

    yvalues = [node.yvalue for node in tree.find_clades()]
    y_span = max(yvalues)
    y_unit = y_span / float(len(yvalues))

    # Setup colors.
    if color_by_trait:
        trait_name = color_by_trait

        if cmap is None:
            traits = [k.attr[trait_name] for k in tree.find_clades()]
            norm = mpl.colors.Normalize(min(traits), max(traits))
            cmap = mpl.cm.viridis

    #
    # Setup the figure grid.
    #

    if ax is None:
        if include_color_bar:
            fig = plt.figure(figsize=(8, 6), facecolor='w')
            gs = gridspec.GridSpec(2, 1, height_ratios=[14, 1], width_ratios=[1], hspace=0.1, wspace=0.1)
            ax = fig.add_subplot(gs[0])
            colorbar_ax = fig.add_subplot(gs[1])
        else:
            fig = plt.figure(figsize=(8, 4), facecolor='w')
            gs = gridspec.GridSpec(1, 1)
            ax = fig.add_subplot(gs[0])

    L=len([k for k in tree.find_clades() if k.is_terminal()])

    # Setup arrays for tip and internal node coordinates.
    tip_circles_x = []
    tip_circles_y = []
    tip_circles_color = []
    tip_circle_sizes = []
    node_circles_x = []
    node_circles_y = []
    node_circles_color = []
    node_line_widths = []
    node_line_segments = []
    node_line_colors = []
    branch_line_segments = []
    branch_line_widths = []
    branch_line_colors = []
    branch_line_labels = []

    for k in tree.find_clades(): ## iterate over objects in tree
        x=k.attr["num_date"] ## or from x position determined earlier

        if earliest_node_date and x < earliest_node_date:
            continue

        if k.name in override_y_values:
            y = override_y_values[k.name]
        else:
            y = y_span - k.yvalue ## get y position from .drawTree that was run earlier, but could be anything else

        if k.parent is None:
            xp = None
        else:
            xp=k.parent.attr["num_date"] ## get x position of current object's parent

        if x==None: ## matplotlib won't plot Nones, like root
            x=0.0
        if xp==None:
            xp=x

        c = default_color
        if color_by_trait and trait_name in k.attr:
            if isinstance(cmap, dict):
                c = cmap[k.attr[trait_name]]
            else:
                c = cmap(norm(k.attr[trait_name]))

        branchWidth=2
        if k.is_terminal(): ## if leaf...
            s = tip_size ## tip size can be fixed

            tip_circle_sizes.append(s)
            tip_circles_x.append(x)
            tip_circles_y.append(y)
            tip_circles_color.append(c)
        else: ## if node...
            k_leaves = [child
                        for child in k.find_clades()
                        if child.is_terminal()]

            # Scale branch widths by the number of tips.
            branchWidth += initial_branch_width * len(k_leaves) / float(L)

            if len(k.clades)==1:
                node_circles_x.append(x)
                node_circles_y.append(y)
                node_circles_color.append(c)

            ax.plot([x,x],[y_span - k.clades[-1].yvalue, y_span - k.clades[0].yvalue], lw=branchWidth, color=c, ls='-', zorder=9, solid_capstyle='round')

        branch_line_segments.append([(xp, y), (x, y)])
        branch_line_widths.append(branchWidth)
        branch_line_colors.append(c)

    branch_lc = LineCollection(branch_line_segments, zorder=9)
    branch_lc.set_color(branch_line_colors)
    branch_lc.set_linewidth(branch_line_widths)
    branch_lc.set_label(branch_line_labels)
    branch_lc.set_linestyle("-")
    ax.add_collection(branch_lc)

    # Add circles for tips and internal nodes.
    tip_circle_sizes = np.array(tip_circle_sizes)
    ax.scatter(tip_circles_x, tip_circles_y, s=tip_circle_sizes, facecolor=tip_circles_color, edgecolor='none',zorder=11) ## plot circle for every tip
    ax.scatter(tip_circles_x, tip_circles_y, s=tip_circle_sizes*2, facecolor='k', edgecolor='none', zorder=10) ## plot black circle underneath
    ax.scatter(node_circles_x, node_circles_y, facecolor=node_circles_color, s=50, edgecolor='none', zorder=10, lw=2, marker='|') ## mark every node in the tree to highlight that it's a multitype tree

    #ax.set_ylim(-10, y_span - 300)

    ax.spines['top'].set_visible(False) ## no axes
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)

    ax.tick_params(axis='y',size=0)
    ax.set_yticklabels([])

    if start_date:
        ax.set_xlim(left=start_date)

    if end_date:
        ax.set_xlim(right=end_date)

    if include_color_bar:
        cb1 = mpl.colorbar.ColorbarBase(
            colorbar_ax,
            cmap=cmap,
            norm=norm,
            orientation='horizontal'
        )
        cb1.set_label(color_by_trait)

    return ax, colorbar_ax
```

```python
fig = plt.figure(figsize=(6, 4), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.grid(axis='x',ls='-',color='grey')
```

## Plot next tree

This tree includes samples from the next year since the origin tree.

```python
fig = plt.figure(figsize=(6, 4), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(next_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
```

## Overlay the two trees

Plot all nodes from both trees.

```python
earliest_node_date = max([node.attr["num_date"] for node in origin_tree.find_clades(terminal=True)])
```

```python
earliest_node_date
```

    2001.7419575633128

```python
origin_y_values = [node.yvalue for node in origin_tree.find_clades()]
max_origin_y = max(origin_y_values)
override_y_values = {node.name: max_origin_y - node.yvalue for node in origin_tree.find_clades(terminal=True)}

max_next_y = max([node.yvalue for node in next_tree.find_clades()])
max_y = max(max_origin_y, max_next_y)
```

```python
max_y
```

    333

```python
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.set_ylim(top=max_y + 10)
```

```python
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")
ax.set_ylim(top=max_y + 10)
```

```python
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=None,
    default_color="powderblue",
    tip_size=tip_size
)

ax.set_ylim(top=max_y + 10)
```

```python
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=None,
    default_color="powderblue",
    tip_size=tip_size,
    override_y_values=override_y_values
)

ax.set_ylim(top=max_y + 10)
```

Now plot only nodes from the next tree since the last sample in the origin tree.

```python
tip_size = 14
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=earliest_node_date,
    default_color="powderblue",
    tip_size=tip_size
)
ax.set_ylim(top=max_y + 10)
```

Highlight the training and validation windows.

```python
tip_size = 14
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(origin_tree, ax=ax, start_date=1993.0, end_date=end_date, tip_size=tip_size)
#ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=earliest_node_date,
    tip_size=tip_size
)
ax.set_ylim(top=max_y + 10)

# Highlight training window.
rectangle = plt.Rectangle((1994.75, 0), 6.0, max_y, fc='#00cc00',
                          alpha=0.2, zorder=-10)
ax.add_patch(rectangle)

# Highlight validation window.
rectangle = plt.Rectangle((2001.75, 0), 1.0, max_y, fc='#ffcc33',
                          alpha=0.5, zorder=-10)
ax.add_patch(rectangle)

ax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)

ax.grid(
    axis='x',
    ls='-',
    color='#cccccc',
    alpha=0.5,
    which="minor"
)
```

```python
origin_tips = {tip.name: tip.attr["num_date"] for tip in origin_tree.find_clades(terminal=True)}
next_tips = {tip.name: tip.attr["num_date"] for tip in next_tree.find_clades(terminal=True)}
```

```python
len(next_tips)
```

    333

```python
len(origin_tips)
```

    269

```python
earliest_node_date
```

    2001.7419575633128

```python
[(tip, date) for tip, date in next_tips.items() if tip not in origin_tips and date <= earliest_node_date]
```

    []

```python
for tip in [tip for tip, date in next_tips.items() if tip not in origin_tips and date <= earliest_node_date]:
    print(tip)
```

```python
clades = set()
for node in origin_tree.find_clades():
    clades.add(node.attr["clade_membership"])

for node in next_tree.find_clades():
    if node.attr["num_date"] > earliest_node_date:
        clades.add(node.attr["clade_membership"])
```

```python
len(clades)
```

    37

```python
cmap = plt.get_cmap("tab20")
```

```python
color_by_clade = {clade: cmap(i % 20) for i, clade in enumerate(clades)}
```

```python
tip_size = 14
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(
    origin_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    tip_size=tip_size,
    color_by_trait="clade_membership",
    cmap=color_by_clade,
    default_color="#ffffff"
)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=earliest_node_date,
    tip_size=tip_size,
    color_by_trait="clade_membership",
    cmap=color_by_clade,
    default_color="#ffffff"
)
ax.set_ylim(top=max_y + 10)

ax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)

ax.grid(
    axis='x',
    ls='-',
    color='#cccccc',
    alpha=0.5,
    which="minor"
)
```

```python
final_tips_by_clades = pd.read_table("../results/builds/h3n2/10_viruses_per_month/sample_0/1994-10-01--2015-10-01/final_clade_frequencies.tsv")
```

```python
final_tips_by_clades.head()
```

      initial_timepoint
      clade_membership
      final_timepoint
      strain
      frequency

      0
      1996-10-01
      02e323e
      1997-10-01
      A/Auckland/10/1997
      0.035959

      1
      1996-10-01
      02e323e
      1997-10-01
      A/HongKong/CUHK12160/1997
      0.033047

      2
      1996-10-01
      02e323e
      1997-10-01
      A/HongKong/CUHK12563/1997
      0.036006

      3
      1996-10-01
      02e323e
      1997-10-01
      A/HongKong/CUHK12626/1997
      0.036066

      4
      1996-10-01
      02e323e
      1997-10-01
      A/HongKong/CUHK20236/1997
      0.036691

```python
tips_to_previous_clades = dict(
    final_tips_by_clades.loc[final_tips_by_clades["initial_timepoint"] == "2001-10-01", ["strain", "clade_membership"]].values
)
```

```python
for tip in next_tree.find_clades(terminal=True):
    if tip.name in tips_to_previous_clades:
        tip.attr["previous_clade_membership"] = tips_to_previous_clades[tip.name]
    elif tip.attr["num_date"] > earliest_node_date:
        print(tip)
```

    A/HongKong/CUHK50080/2001
    A/HongKong/CUHK50200/2002
    A/NewYork/55/2001
    A/NewYork/71/2001
    A/NewYork/401/2001
    A/WesternAustralia/17/2001
    A/Auckland/603/2001

```python
tip_size = 14
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(
    origin_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    tip_size=tip_size,
    color_by_trait="clade_membership",
    cmap=color_by_clade,
    default_color="#ffffff"
)
ax.axvline(x=earliest_node_date, color="#999999", linestyle="--")

ax, colorbar_ax = plot_tree(
    next_tree,
    ax=ax,
    start_date=1993.0,
    end_date=end_date,
    earliest_node_date=earliest_node_date,
    tip_size=tip_size,
    color_by_trait="previous_clade_membership",
    cmap=color_by_clade,
    default_color="#ffffff"
    #override_y_values=override_y_values
)
ax.set_ylim(top=max_y + 10)

ax.set_xticks(np.arange(1994.75, 2003.25, 0.5), minor=True)

ax.grid(
    axis='x',
    ls='-',
    color='#cccccc',
    alpha=0.5,
    which="minor"
)
```

```python
tips_to_clades.head()
```

      tip
      clade_membership
      depth
      lineage
      segment
      timepoint

      0
      A/NewYork/657/1994
      726b03c
      0
      h3n2
      ha
      1996-10-01

      1
      A/NewYork/657/1994
      f8b9dde
      2
      h3n2
      ha
      1996-10-01

      2
      A/NewYork/657/1994
      root
      3
      h3n2
      ha
      1996-10-01

      3
      A/HongKong/42/1996
      34f68f9
      0
      h3n2
      ha
      1996-10-01

      4
      A/HongKong/42/1996
      726b03c
      1
      h3n2
      ha
      1996-10-01

```python
tips_to_clades[(tips_to_clades["tip"] == "A/Auckland/603/2001") & (tips_to_clades["timepoint"] == "2002-10-01")]
```

      tip
      clade_membership
      depth
      lineage
      segment
      timepoint

      21284
      A/Auckland/603/2001
      fbbd597
      0
      h3n2
      ha
      2002-10-01

      21285
      A/Auckland/603/2001
      5bed3da
      7
      h3n2
      ha
      2002-10-01

      21286
      A/Auckland/603/2001
      05a6dc1
      8
      h3n2
      ha
      2002-10-01

      21287
      A/Auckland/603/2001
      f39e6da
      10
      h3n2
      ha
      2002-10-01

      21288
      A/Auckland/603/2001
      048f8ca
      11
      h3n2
      ha
      2002-10-01

      21289
      A/Auckland/603/2001
      e64cc68
      15
      h3n2
      ha
      2002-10-01

      21290
      A/Auckland/603/2001
      e2f3876
      16
      h3n2
      ha
      2002-10-01

      21291
      A/Auckland/603/2001
      d6906cf
      17
      h3n2
      ha
      2002-10-01

      21292
      A/Auckland/603/2001
      88dab64
      18
      h3n2
      ha
      2002-10-01

      21293
      A/Auckland/603/2001
      98c068a
      19
      h3n2
      ha
      2002-10-01

      21294
      A/Auckland/603/2001
      09e68a2
      21
      h3n2
      ha
      2002-10-01

      21295
      A/Auckland/603/2001
      e501908
      22
      h3n2
      ha
      2002-10-01

      21296
      A/Auckland/603/2001
      ecf49fd
      23
      h3n2
      ha
      2002-10-01

      21297
      A/Auckland/603/2001
      d7fecad
      25
      h3n2
      ha
      2002-10-01

      21298
      A/Auckland/603/2001
      02e323e
      26
      h3n2
      ha
      2002-10-01

      21299
      A/Auckland/603/2001
      35491c6
      27
      h3n2
      ha
      2002-10-01

      21300
      A/Auckland/603/2001
      root
      29
      h3n2
      ha
      2002-10-01

```python
tips_to_clades[(tips_to_clades["clade_membership"] == "fbbd597") & (tips_to_clades["timepoint"] == "2001-10-01")]
```

      tip
      clade_membership
      depth
      lineage
      segment
      timepoint

      14117
      A/WesternAustralia/15/2001
      fbbd597
      2
      h3n2
      ha
      2001-10-01

      14135
      A/WesternAustralia/16/2001
      fbbd597
      2
      h3n2
      ha
      2001-10-01

      14152
      A/Queensland/14/2001
      fbbd597
      0
      h3n2
      ha
      2001-10-01

      14169
      A/Queensland/20/2001
      fbbd597
      0
      h3n2
      ha
      2001-10-01

      14187
      A/Auckland/604/2001
      fbbd597
      2
      h3n2
      ha
      2001-10-01

      14205
      A/Waikato/105/2001
      fbbd597
      2
      h3n2
      ha
      2001-10-01

      14223
      A/Auckland/602/2001
      fbbd597
      2
      h3n2
      ha
      2001-10-01

```python
"fbbd597" in clades
```

    True

## Plot a subtree to demonstrate predictors

```python
subtree = None
potential_subtrees = [node for node in origin_tree.find_clades(terminal=False)
                      if node.count_terminals() == 5]
```

```python
len(potential_subtrees)
```

    15

```python
subtree = potential_subtrees[2]
```

```python
fig = plt.figure(figsize=(8, 6), facecolor='w')
gs = gridspec.GridSpec(1, 1, height_ratios=[1], width_ratios=[1], hspace=0.1, wspace=0.1)
ax = fig.add_subplot(gs[0])

ax, colorbar_ax = plot_tree(subtree, tip_size=30, initial_branch_width=5, ax=ax)
ax.set_xticks([])
ax.spines['bottom'].set_visible(False)
```

## Math equations for predictors

Delta frequency:

$$\frac{\Delta{x}}{\Delta{t}}$$

Information gain:

$$
\sum_{v \in K(t)}{Y_{v}(t + 1) \log{\frac{\hat{Y}_{v}(t + 1)}{Y_v{}(t)}}}
$$

The epitope cross-immunity predictor is defined as follows:

$$
f_{i}^{ep\_x} = f_{0} - \sigma_{ep\_x} \sum_{j:t_{j} < t_{i}}{x_{j}c(D_{ep}(a_{i}, a_{j}))}
$$

where $\sigma_{ep}$ is a parameter learned from data.

The function $c(D_{ep})$ is defined as follows:

$$
c(D_{ep}) = \exp(-D_{ep} / D_{0})
$$

### Hamming distance

Weighted Hamming distance between viruses a and m:

$$
(x_{a}\exp{(f_{a}\Delta{t})})(x_{m})(d_{am})
$$

General weighted Hamming distance between virus a and all other future viruses:

$$
H_{a} = x_{m}d_{am} + x_{n}d_{an} + x_{o}d_{ao}
$$

Then the overall weighted Hamming distance between all viruses at time t and t + 1 is given by:

$$
H(t) = H_{a}x_{a}\exp{(f_{a}\Delta{t})} + H_{b}x_{b}\exp{(f_{b}\Delta{t})} + H_{c}x_{c}\exp{(f_{c}\Delta{t})}
$$

Actually, I think there is a problem with the above logic since there is not an estimator for the future Hamming distance but only a calculation of observed Hamming distance.

The observed weighted Hamming distance between virus a and all viruses in the next year would be:

$$
\begin{align}
H_{a}(t + 1) = x_{a}(t)(x_{m}(t + 1)d_{am} + \\
                        x_{n}(t + 1)d_{an} + \\
                        x_{o}(t + 1)d_{ao})
\end{align}
$$

The estimated weighted Hamming distance when forecasting cannot include distances from future sequences. Instead, I think we need to estimate the composition of the future timepoint by projecting the current viruses forward by their fitnesses. The estimated distance is then between current and projected frequencies of viruses at the current timepoint.

$$
\begin{align}
\hat{H}_{a}(t + 1) = x_{a}(t)(x_{a}(t)\exp{(f_{a}\Delta{t})}d_{aa} + \\
                              x_{b}(t)\exp{(f_{b}\Delta{t})}d_{ab} + \\
                              x_{c}(t)\exp{(f_{c}\Delta{t})}d_{ac})
\end{align}
$$

Or, a more computationally efficient approach for optimization would be:

$$
\begin{align}
\hat{H}(t + 1) = x_{a}(t)\exp{(f_{a}\Delta{t})}(x_{b}(t)d_{ba} + x_{c}(t)d_{ca}) + \\
                 x_{b}(t)\exp{(f_{b}\Delta{t})}(x_{a}(t)d_{ab} + x_{c}(t)d_{cb}) + \\
                 x_{c}(t)\exp{(f_{c}\Delta{t})}(x_{a}(t)d_{ac} + x_{b}(t)d_{bc})
\end{align}
$$

```python

```


## 其他的迭代环境

### 1. for 循环使用了迭代协议；
### 2. 任何从左到右扫描对象的工具都使用迭代协议；

```python
for line in open('untitled3.py'):
    print(line.upper(), end = '')
```

    # -*- CODING: UTF-8 -*-
    """
    CREATED ON TUE FEB 18 22:04:07 2020

    @AUTHOR: NICKC
    """

    #KOCHEDRAW1
    IMPORT TURTLE
    DEF KOCH(SIZE,N):
      IF N==1:
        TURTLE.FD(SIZE)
      ELSE:
        FOR I IN [0,60,-120,60]:
          TURTLE.LEFT(I)
          KOCH(SIZE/3,N-1)
    DEF MAIN():
      TURTLE.SETUP(600,600)
      TURTLE.PENUP()
      TURTLE.SPEED(10)
      TURTLE.HIDETURTLE()
      TURTLE.PENSIZE(2)
      TURTLE.GOTO(-200,100)
      TURTLE.PENDOWN()
      LEVEL=4
      KOCH(400,LEVEL)
      TURTLE.RIGHT(120)
      KOCH(400, LEVEL)
      TURTLE.RIGHT(120)
      KOCH(400, LEVEL)
      TURTLE.PENUP()
      TURTLE.DONE()
    MAIN()

### 列表解析，in的子集测试，内置函数map, sorted, zip 都会使用迭代协议

```python
uppers = [line.upper() for line in open('untitled3.py')] #列表解析
```

```python
uppers
```

    ['# -*- CODING: UTF-8 -*-\n',
     '"""\n',
     'CREATED ON TUE FEB 18 22:04:07 2020\n',
     '\n',
     '@AUTHOR: NICKC\n',
     '"""\n',
     '\n',
     '#KOCHEDRAW1\n',
     'IMPORT TURTLE\n',
     'DEF KOCH(SIZE,N):\n',
     '  IF N==1:\n',
     '    TURTLE.FD(SIZE)\n',
     '  ELSE:\n',
     '    FOR I IN [0,60,-120,60]:\n',
     '      TURTLE.LEFT(I)\n',
     '      KOCH(SIZE/3,N-1)\n',
     'DEF MAIN():\n',
     '  TURTLE.SETUP(600,600)\n',
     '  TURTLE.PENUP()\n',
     '  TURTLE.SPEED(10)\n',
     '  TURTLE.HIDETURTLE()\n',
     '  TURTLE.PENSIZE(2)\n',
     '  TURTLE.GOTO(-200,100)\n',
     '  TURTLE.PENDOWN()\n',
     '  LEVEL=4\n',
     '  KOCH(400,LEVEL)\n',
     '  TURTLE.RIGHT(120)\n',
     '  KOCH(400, LEVEL)\n',
     '  TURTLE.RIGHT(120)\n',
     '  KOCH(400, LEVEL)\n',
     '  TURTLE.PENUP()\n',
     '  TURTLE.DONE()\n',
     'MAIN()']

```python
'@AUTHOR: NICKC\n' in open('untitled3.py').read().upper() # in的子集测试
```

    True

```python
map(str.upper, open('untitled3.py')) # map内置函数
```

    <map at 0x17ac5bdd608>

```python
list(map(str.upper, open('untitled3.py')))
```

    ['# -*- CODING: UTF-8 -*-\n',
     '"""\n',
     'CREATED ON TUE FEB 18 22:04:07 2020\n',
     '\n',
     '@AUTHOR: NICKC\n',
     '"""\n',
     '\n',
     '#KOCHEDRAW1\n',
     'IMPORT TURTLE\n',
     'DEF KOCH(SIZE,N):\n',
     '  IF N==1:\n',
     '    TURTLE.FD(SIZE)\n',
     '  ELSE:\n',
     '    FOR I IN [0,60,-120,60]:\n',
     '      TURTLE.LEFT(I)\n',
     '      KOCH(SIZE/3,N-1)\n',
     'DEF MAIN():\n',
     '  TURTLE.SETUP(600,600)\n',
     '  TURTLE.PENUP()\n',
     '  TURTLE.SPEED(10)\n',
     '  TURTLE.HIDETURTLE()\n',
     '  TURTLE.PENSIZE(2)\n',
     '  TURTLE.GOTO(-200,100)\n',
     '  TURTLE.PENDOWN()\n',
     '  LEVEL=4\n',
     '  KOCH(400,LEVEL)\n',
     '  TURTLE.RIGHT(120)\n',
     '  KOCH(400, LEVEL)\n',
     '  TURTLE.RIGHT(120)\n',
     '  KOCH(400, LEVEL)\n',
     '  TURTLE.PENUP()\n',
     '  TURTLE.DONE()\n',
     'MAIN()']

```python
f = open('untitled3.py')
enumerate(map(f.readline, open('untitled3.py'))) # map的function选项取决于后面作用对象的类型
```

    <enumerate at 0x17ac5d4f688>

```python
open('untitled3.py').readline()
```

    '# -*- coding: utf-8 -*-\n'

```python
[line for line in open('untitled3.py')]
```

    ['# -*- coding: utf-8 -*-\n',
     '"""\n',
     'Created on Tue Feb 18 22:04:07 2020\n',
     '\n',
     '@author: NickC\n',
     '"""\n',
     '\n',
     '#KocheDraw1\n',
     'import turtle\n',
     'def koch(size,n):\n',
     '  if n==1:\n',
     '    turtle.fd(size)\n',
     '  else:\n',
     '    for i in [0,60,-120,60]:\n',
     '      turtle.left(i)\n',
     '      koch(size/3,n-1)\n',
     'def main():\n',
     '  turtle.setup(600,600)\n',
     '  turtle.penup()\n',
     '  turtle.speed(10)\n',
     '  turtle.hideturtle()\n',
     '  turtle.pensize(2)\n',
     '  turtle.goto(-200,100)\n',
     '  turtle.pendown()\n',
     '  level=4\n',
     '  koch(400,level)\n',
     '  turtle.right(120)\n',
     '  koch(400, level)\n',
     '  turtle.right(120)\n',
     '  koch(400, level)\n',
     '  turtle.penup()\n',
     '  turtle.done()\n',
     'main()']

```python
def function(x):
    return x+' \n'+ x
```

```python
list(map(function, open('untitled3.py')))
```

    ['# -*- coding: utf-8 -*-\n \n# -*- coding: utf-8 -*-\n',
     '"""\n \n"""\n',
     'Created on Tue Feb 18 22:04:07 2020\n \nCreated on Tue Feb 18 22:04:07 2020\n',
     '\n \n\n',
     '@author: NickC\n \n@author: NickC\n',
     '"""\n \n"""\n',
     '\n \n\n',
     '#KocheDraw1\n \n#KocheDraw1\n',
     'import turtle\n \nimport turtle\n',
     'def koch(size,n):\n \ndef koch(size,n):\n',
     '  if n==1:\n \n  if n==1:\n',
     '    turtle.fd(size)\n \n    turtle.fd(size)\n',
     '  else:\n \n  else:\n',
     '    for i in [0,60,-120,60]:\n \n    for i in [0,60,-120,60]:\n',
     '      turtle.left(i)\n \n      turtle.left(i)\n',
     '      koch(size/3,n-1)\n \n      koch(size/3,n-1)\n',
     'def main():\n \ndef main():\n',
     '  turtle.setup(600,600)\n \n  turtle.setup(600,600)\n',
     '  turtle.penup()\n \n  turtle.penup()\n',
     '  turtle.speed(10)\n \n  turtle.speed(10)\n',
     '  turtle.hideturtle()\n \n  turtle.hideturtle()\n',
     '  turtle.pensize(2)\n \n  turtle.pensize(2)\n',
     '  turtle.goto(-200,100)\n \n  turtle.goto(-200,100)\n',
     '  turtle.pendown()\n \n  turtle.pendown()\n',
     '  level=4\n \n  level=4\n',
     '  koch(400,level)\n \n  koch(400,level)\n',
     '  turtle.right(120)\n \n  turtle.right(120)\n',
     '  koch(400, level)\n \n  koch(400, level)\n',
     '  turtle.right(120)\n \n  turtle.right(120)\n',
     '  koch(400, level)\n \n  koch(400, level)\n',
     '  turtle.penup()\n \n  turtle.penup()\n',
     '  turtle.done()\n \n  turtle.done()\n',
     'main() \nmain()']

```python
from sympy import tanh
def function(x):
    return tanh(x).evalf()
```

```python
list(map(function,list(range(1,101))))
```

    [0.761594155955765,
     0.964027580075817,
     0.995054753686730,
     0.999329299739067,
     0.999909204262595,
     0.999987711650796,
     0.999998336943945,
     0.999999774929676,
     0.999999969540041,
     0.999999995877693,
     0.999999999442106,
     0.999999999924497,
     0.999999999989782,
     0.999999999998617,
     0.999999999999813,
     0.999999999999975,
     0.999999999999997,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000,
     1.00000000000000]

### map很像列表解析，但是没有列表解析强大，map需要函数而列表解析可以是任意的表达式

```python
S = """Python includes various additional built-ins that process iterables, too: sorted sorts
items in an iterable, zip combines items from iterables, enumerate pairs items in an
iterable with relative positions, filter selects items for which a function is true, and
reduce runs pairs of items in an iterable through a function. All of these accept iterables,
and zip, enumerate, and filter also return an iterable in Python 3.0, like map. Here they
are in action running the file’s iterator automatically to scan line by line:""" # S 是个字符串
```

```python
L = S.split()
print(L, end='')
```

    ['Python', 'includes', 'various', 'additional', 'built-ins', 'that', 'process', 'iterables,', 'too:', 'sorted', 'sorts', 'items', 'in', 'an', 'iterable,', 'zip', 'combines', 'items', 'from', 'iterables,', 'enumerate', 'pairs', 'items', 'in', 'an', 'iterable', 'with', 'relative', 'positions,', 'filter', 'selects', 'items', 'for', 'which', 'a', 'function', 'is', 'true,', 'and', 'reduce', 'runs', 'pairs', 'of', 'items', 'in', 'an', 'iterable', 'through', 'a', 'function.', 'All', 'of', 'these', 'accept', 'iterables,', 'and', 'zip,', 'enumerate,', 'and', 'filter', 'also', 'return', 'an', 'iterable', 'in', 'Python', '3.0,', 'like', 'map.', 'Here', 'they', 'are', 'in', 'action', 'running', 'the', 'file’s', 'iterator', 'automatically', 'to', 'scan', 'line', 'by', 'line:']

```python
print(sorted(L), end = '') # 字符串首先是从1-100，从A到Z, 再从a到z
```

    ['3.0,', 'All', 'Here', 'Python', 'Python', 'a', 'a', 'accept', 'action', 'additional', 'also', 'an', 'an', 'an', 'an', 'and', 'and', 'and', 'are', 'automatically', 'built-ins', 'by', 'combines', 'enumerate', 'enumerate,', 'file’s', 'filter', 'filter', 'for', 'from', 'function', 'function.', 'in', 'in', 'in', 'in', 'in', 'includes', 'is', 'items', 'items', 'items', 'items', 'items', 'iterable', 'iterable', 'iterable', 'iterable,', 'iterables,', 'iterables,', 'iterables,', 'iterator', 'like', 'line', 'line:', 'map.', 'of', 'of', 'pairs', 'pairs', 'positions,', 'process', 'reduce', 'relative', 'return', 'running', 'runs', 'scan', 'selects', 'sorted', 'sorts', 'that', 'the', 'these', 'they', 'through', 'to', 'too:', 'true,', 'various', 'which', 'with', 'zip', 'zip,']

```python
L1 = []
from numpy import random
for i in range(100):
    L1.append(random.randint(100))
```

```python
print(L1, end = '' )
```

    [10, 94, 39, 44, 19, 20, 78, 98, 40, 26, 48, 47, 60, 26, 91, 50, 94, 40, 34, 62, 93, 16, 0, 28, 40, 3, 55, 25, 46, 60, 90, 58, 68, 97, 50, 90, 9, 20, 69, 9, 33, 41, 65, 68, 73, 63, 70, 65, 77, 30, 28, 60, 11, 18, 44, 32, 94, 40, 19, 93, 13, 81, 42, 40, 85, 72, 74, 2, 50, 69, 77, 73, 44, 69, 80, 67, 11, 56, 6, 21, 89, 12, 91, 79, 63, 84, 71, 66, 65, 27, 71, 22, 45, 19, 4, 92, 44, 67, 92, 46]

```python
print(sorted(L), end= '')
```

    [1, 1, 3, 3, 3, 4, 4, 4, 4, 6, 7, 8, 9, 10, 11, 11, 12, 12, 13, 14, 16, 17, 17, 19, 20, 21, 25, 27, 27, 28, 29, 29, 32, 32, 34, 35, 37, 38, 39, 43, 43, 44, 44, 45, 46, 48, 48, 49, 50, 51, 51, 53, 53, 54, 56, 58, 59, 59, 60, 60, 61, 61, 62, 63, 65, 65, 67, 67, 68, 72, 74, 75, 75, 76, 76, 76, 79, 82, 82, 82, 83, 84, 85, 85, 87, 87, 88, 88, 89, 89, 89, 90, 92, 93, 93, 97, 97, 97, 98, 98]

```python
L2 = []
for i in range(100,200):
    L2.append(random.randint(100,200))
```

```python
print(L2, end='')
```

    [180, 158, 169, 160, 175, 132, 100, 110, 185, 187, 147, 117, 182, 156, 196, 196, 142, 158, 142, 156, 167, 178, 106, 177, 191, 106, 187, 190, 134, 184, 166, 104, 154, 131, 111, 157, 193, 150, 157, 192, 102, 140, 180, 103, 148, 197, 190, 179, 171, 117, 190, 188, 113, 129, 149, 171, 158, 145, 166, 104, 100, 191, 118, 136, 134, 148, 157, 117, 166, 171, 108, 135, 190, 119, 132, 181, 173, 142, 174, 142, 114, 111, 111, 170, 139, 153, 151, 170, 195, 198, 178, 197, 196, 115, 189, 193, 139, 103, 191, 165]

```python
print(list(zip(L1, L2)), end= '')
```

    [(10, 180), (94, 158), (39, 169), (44, 160), (19, 175), (20, 132), (78, 100), (98, 110), (40, 185), (26, 187), (48, 147), (47, 117), (60, 182), (26, 156), (91, 196), (50, 196), (94, 142), (40, 158), (34, 142), (62, 156), (93, 167), (16, 178), (0, 106), (28, 177), (40, 191), (3, 106), (55, 187), (25, 190), (46, 134), (60, 184), (90, 166), (58, 104), (68, 154), (97, 131), (50, 111), (90, 157), (9, 193), (20, 150), (69, 157), (9, 192), (33, 102), (41, 140), (65, 180), (68, 103), (73, 148), (63, 197), (70, 190), (65, 179), (77, 171), (30, 117), (28, 190), (60, 188), (11, 113), (18, 129), (44, 149), (32, 171), (94, 158), (40, 145), (19, 166), (93, 104), (13, 100), (81, 191), (42, 118), (40, 136), (85, 134), (72, 148), (74, 157), (2, 117), (50, 166), (69, 171), (77, 108), (73, 135), (44, 190), (69, 119), (80, 132), (67, 181), (11, 173), (56, 142), (6, 174), (21, 142), (89, 114), (12, 111), (91, 111), (79, 170), (63, 139), (84, 153), (71, 151), (66, 170), (65, 195), (27, 198), (71, 178), (22, 197), (45, 196), (19, 115), (4, 189), (92, 193), (44, 139), (67, 103), (92, 191), (46, 165)]

```python
print(list(enumerate(S.split(sep='.'))))
```

    [(0, 'Python includes various additional built-ins that process iterables, too: sorted sorts\nitems in an iterable, zip combines items from iterables, enumerate pairs items in an\niterable with relative positions, filter selects items for which a function is true, and\nreduce runs pairs of items in an iterable through a function'), (1, ' All of these accept iterables,\nand zip, enumerate, and filter also return an iterable in Python 3'), (2, '0, like map'), (3, ' Here they\nare in action running the file’s iterator automatically to scan line by line:')]

```python
print(list(filter(str.isalpha, S.split()))) # 当str.isalpha是正确的时候，元素就会过滤起来
```

    ['Python', 'includes', 'various', 'additional', 'that', 'process', 'sorted', 'sorts', 'items', 'in', 'an', 'zip', 'combines', 'items', 'from', 'enumerate', 'pairs', 'items', 'in', 'an', 'iterable', 'with', 'relative', 'filter', 'selects', 'items', 'for', 'which', 'a', 'function', 'is', 'and', 'reduce', 'runs', 'pairs', 'of', 'items', 'in', 'an', 'iterable', 'through', 'a', 'All', 'of', 'these', 'accept', 'and', 'and', 'filter', 'also', 'return', 'an', 'iterable', 'in', 'Python', 'like', 'Here', 'they', 'are', 'in', 'action', 'running', 'the', 'iterator', 'automatically', 'to', 'scan', 'line', 'by']

```python
sorted(open('untitled3.py'))
```

    ['\n',
     '\n',
     '      koch(size/3,n-1)\n',
     '      turtle.left(i)\n',
     '    for i in [0,60,-120,60]:\n',
     '    turtle.fd(size)\n',
     '  else:\n',
     '  if n==1:\n',
     '  koch(400, level)\n',
     '  koch(400, level)\n',
     '  koch(400,level)\n',
     '  level=4\n',
     '  turtle.done()\n',
     '  turtle.goto(-200,100)\n',
     '  turtle.hideturtle()\n',
     '  turtle.pendown()\n',
     '  turtle.pensize(2)\n',
     '  turtle.penup()\n',
     '  turtle.penup()\n',
     '  turtle.right(120)\n',
     '  turtle.right(120)\n',
     '  turtle.setup(600,600)\n',
     '  turtle.speed(10)\n',
     '"""\n',
     '"""\n',
     '# -*- coding: utf-8 -*-\n',
     '#KocheDraw1\n',
     '@author: NickC\n',
     'Created on Tue Feb 18 22:04:07 2020\n',
     'def koch(size,n):\n',
     'def main():\n',
     'import turtle\n',
     'main()']

```python
list(zip(open("untitled3.py"), open("untitled3.py")))
```

    [('# -*- coding: utf-8 -*-\n', '# -*- coding: utf-8 -*-\n'),
     ('"""\n', '"""\n'),
     ('Created on Tue Feb 18 22:04:07 2020\n',
      'Created on Tue Feb 18 22:04:07 2020\n'),
     ('\n', '\n'),
     ('@author: NickC\n', '@author: NickC\n'),
     ('"""\n', '"""\n'),
     ('\n', '\n'),
     ('#KocheDraw1\n', '#KocheDraw1\n'),
     ('import turtle\n', 'import turtle\n'),
     ('def koch(size,n):\n', 'def koch(size,n):\n'),
     ('  if n==1:\n', '  if n==1:\n'),
     ('    turtle.fd(size)\n', '    turtle.fd(size)\n'),
     ('  else:\n', '  else:\n'),
     ('    for i in [0,60,-120,60]:\n', '    for i in [0,60,-120,60]:\n'),
     ('      turtle.left(i)\n', '      turtle.left(i)\n'),
     ('      koch(size/3,n-1)\n', '      koch(size/3,n-1)\n'),
     ('def main():\n', 'def main():\n'),
     ('  turtle.setup(600,600)\n', '  turtle.setup(600,600)\n'),
     ('  turtle.penup()\n', '  turtle.penup()\n'),
     ('  turtle.speed(10)\n', '  turtle.speed(10)\n'),
     ('  turtle.hideturtle()\n', '  turtle.hideturtle()\n'),
     ('  turtle.pensize(2)\n', '  turtle.pensize(2)\n'),
     ('  turtle.goto(-200,100)\n', '  turtle.goto(-200,100)\n'),
     ('  turtle.pendown()\n', '  turtle.pendown()\n'),
     ('  level=4\n', '  level=4\n'),
     ('  koch(400,level)\n', '  koch(400,level)\n'),
     ('  turtle.right(120)\n', '  turtle.right(120)\n'),
     ('  koch(400, level)\n', '  koch(400, level)\n'),
     ('  turtle.right(120)\n', '  turtle.right(120)\n'),
     ('  koch(400, level)\n', '  koch(400, level)\n'),
     ('  turtle.penup()\n', '  turtle.penup()\n'),
     ('  turtle.done()\n', '  turtle.done()\n'),
     ('main()', 'main()')]

```python
list(enumerate(open("untitled3.py")))
```

    [(0, '# -*- coding: utf-8 -*-\n'),
     (1, '"""\n'),
     (2, 'Created on Tue Feb 18 22:04:07 2020\n'),
     (3, '\n'),
     (4, '@author: NickC\n'),
     (5, '"""\n'),
     (6, '\n'),
     (7, '#KocheDraw1\n'),
     (8, 'import turtle\n'),
     (9, 'def koch(size,n):\n'),
     (10, '  if n==1:\n'),
     (11, '    turtle.fd(size)\n'),
     (12, '  else:\n'),
     (13, '    for i in [0,60,-120,60]:\n'),
     (14, '      turtle.left(i)\n'),
     (15, '      koch(size/3,n-1)\n'),
     (16, 'def main():\n'),
     (17, '  turtle.setup(600,600)\n'),
     (18, '  turtle.penup()\n'),
     (19, '  turtle.speed(10)\n'),
     (20, '  turtle.hideturtle()\n'),
     (21, '  turtle.pensize(2)\n'),
     (22, '  turtle.goto(-200,100)\n'),
     (23, '  turtle.pendown()\n'),
     (24, '  level=4\n'),
     (25, '  koch(400,level)\n'),
     (26, '  turtle.right(120)\n'),
     (27, '  koch(400, level)\n'),
     (28, '  turtle.right(120)\n'),
     (29, '  koch(400, level)\n'),
     (30, '  turtle.penup()\n'),
     (31, '  turtle.done()\n'),
     (32, 'main()')]

```python
bool('0'), bool(0), bool('1'), bool('')
```

    (True, False, True, False)

```python
list(filter(bool, open('untitled3.py')))
```

    ['# -*- coding: utf-8 -*-\n',
     '"""\n',
     'Created on Tue Feb 18 22:04:07 2020\n',
     '\n',
     '@author: NickC\n',
     '"""\n',
     '\n',
     '#KocheDraw1\n',
     'import turtle\n',
     'def koch(size,n):\n',
     '  if n==1:\n',
     '    turtle.fd(size)\n',
     '  else:\n',
     '    for i in [0,60,-120,60]:\n',
     '      turtle.left(i)\n',
     '      koch(size/3,n-1)\n',
     'def main():\n',
     '  turtle.setup(600,600)\n',
     '  turtle.penup()\n',
     '  turtle.speed(10)\n',
     '  turtle.hideturtle()\n',
     '  turtle.pensize(2)\n',
     '  turtle.goto(-200,100)\n',
     '  turtle.pendown()\n',
     '  level=4\n',
     '  koch(400,level)\n',
     '  turtle.right(120)\n',
     '  koch(400, level)\n',
     '  turtle.right(120)\n',
     '  koch(400, level)\n',
     '  turtle.penup()\n',
     '  turtle.done()\n',
     'main()']

```python
bool('0'), bool(0), bool('1'), bool('')
```

    (True, False, True, False)

```python
if 0:
    print("Hello world")
if 1:
    print("Hello world")
```

    Hello world

```python
if bool('0'):
    print("Hello world")
if bool(1):
    print("Hello world")
```

    Hello world
    Hello world

```python
bool(""), bool(''), bool("""""")
```

    (False, False, False)

```python
import functools, operator
functools.reduce(operator.add, open('untitled3.py'))
```

    '# -*- coding: utf-8 -*-\n"""\nCreated on Tue Feb 18 22:04:07 2020\n\n@author: NickC\n"""\n\n#KocheDraw1\nimport turtle\ndef koch(size,n):\n  if n==1:\n    turtle.fd(size)\n  else:\n    for i in [0,60,-120,60]:\n      turtle.left(i)\n      koch(size/3,n-1)\ndef main():\n  turtle.setup(600,600)\n  turtle.penup()\n  turtle.speed(10)\n  turtle.hideturtle()\n  turtle.pensize(2)\n  turtle.goto(-200,100)\n  turtle.pendown()\n  level=4\n  koch(400,level)\n  turtle.right(120)\n  koch(400, level)\n  turtle.right(120)\n  koch(400, level)\n  turtle.penup()\n  turtle.done()\nmain()'

```python
functools.reduce?
```

    Docstring:
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    Type:      builtin_function_or_method

```python
S = 'import sys\n' + 'print(sys.path)'
```

```python
S
```

    'import sys\nprint(sys.path)'

### from sympy import tanh # tanh 就不是内置函数

```python
L = list(range(100))
```

```python
from numpy import random
L1 = []
L2 = []
for i in range(100):
    L1.append(random.randint(1,101)) # int 就是integer的缩写， integer是整数的意思
for j in range(100):
    L2.append(random.randint(1,101))
```

```python
print(L1, end=''); print('\n'); print(L2, end='')
```

    [16, 17, 71, 95, 77, 79, 76, 65, 97, 98, 72, 23, 82, 1, 68, 11, 66, 30, 69, 19, 99, 19, 17, 23, 89, 48, 63, 55, 80, 63, 35, 92, 46, 76, 39, 72, 90, 13, 41, 37, 44, 93, 45, 17, 49, 97, 62, 37, 30, 4, 45, 18, 80, 7, 96, 14, 85, 18, 27, 55, 48, 43, 38, 99, 95, 86, 39, 13, 47, 76, 31, 40, 23, 54, 63, 50, 21, 44, 9, 84, 58, 38, 62, 62, 6, 18, 92, 5, 100, 2, 49, 10, 65, 88, 79, 53, 88, 79, 66, 72]

    [52, 60, 95, 5, 57, 8, 74, 93, 18, 46, 86, 24, 66, 71, 8, 90, 13, 38, 85, 24, 88, 95, 83, 27, 76, 52, 29, 35, 79, 54, 29, 27, 92, 57, 8, 70, 28, 95, 90, 41, 53, 86, 77, 93, 16, 18, 14, 5, 97, 3, 25, 44, 68, 57, 37, 78, 72, 46, 74, 33, 87, 52, 77, 40, 62, 64, 34, 60, 62, 65, 74, 22, 93, 40, 71, 32, 24, 6, 80, 4, 76, 46, 67, 33, 20, 40, 41, 19, 77, 54, 82, 80, 27, 99, 100, 80, 95, 37, 28, 44]

```python
type(L1.sort()); print('\n');print(sorted(L2), end='')
```

    [3, 4, 5, 5, 6, 8, 8, 8, 13, 14, 16, 18, 18, 19, 20, 22, 24, 24, 24, 25, 27, 27, 27, 28, 28, 29, 29, 32, 33, 33, 34, 35, 37, 37, 38, 40, 40, 40, 41, 41, 44, 44, 46, 46, 46, 52, 52, 52, 53, 54, 54, 57, 57, 57, 60, 60, 62, 62, 64, 65, 66, 67, 68, 70, 71, 71, 72, 74, 74, 74, 76, 76, 77, 77, 77, 78, 79, 80, 80, 80, 82, 83, 85, 86, 86, 87, 88, 90, 90, 92, 93, 93, 93, 95, 95, 95, 95, 97, 99, 100]

### L1.sort() 对对象本身是即时生效的

```python
print(L1) # L1.sort() 对对象本身是即时生效的
```

    [3, 3, 6, 7, 7, 8, 11, 12, 13, 14, 16, 19, 19, 22, 25, 25, 29, 32, 32, 34, 34, 37, 37, 39, 40, 41, 41, 44, 45, 45, 47, 48, 48, 51, 52, 53, 53, 53, 55, 55, 56, 57, 58, 59, 59, 60, 61, 61, 61, 63, 64, 65, 65, 66, 68, 70, 71, 72, 73, 74, 78, 78, 79, 80, 80, 81, 82, 84, 84, 84, 84, 85, 89, 89, 89, 89, 90, 90, 90, 90, 91, 92, 92, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 97, 97, 97, 97, 98, 99, 99]

### 不是即时生效的例子

```python
a = L1
print( 'a = '+ str(a), end='')
print('\n')
b = a  # b是等于列表L1, 而不是a这个名字
print('b = ' + str(b), end ='')
print('\n')
a = a + L2
print('a = ' + str(a), end= "")
print('\n')
print(b, end='')
```

    a = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]

    b = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]

    a = [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100, 52, 60, 95, 5, 57, 8, 74, 93, 18, 46, 86, 24, 66, 71, 8, 90, 13, 38, 85, 24, 88, 95, 83, 27, 76, 52, 29, 35, 79, 54, 29, 27, 92, 57, 8, 70, 28, 95, 90, 41, 53, 86, 77, 93, 16, 18, 14, 5, 97, 3, 25, 44, 68, 57, 37, 78, 72, 46, 74, 33, 87, 52, 77, 40, 62, 64, 34, 60, 62, 65, 74, 22, 93, 40, 71, 32, 24, 6, 80, 4, 76, 46, 67, 33, 20, 40, 41, 19, 77, 54, 82, 80, 27, 99, 100, 80, 95, 37, 28, 44]

    [1, 2, 4, 5, 6, 7, 9, 10, 11, 13, 13, 14, 16, 17, 17, 17, 18, 18, 18, 19, 19, 21, 23, 23, 23, 27, 30, 30, 31, 35, 37, 37, 38, 38, 39, 39, 40, 41, 43, 44, 44, 45, 45, 46, 47, 48, 48, 49, 49, 50, 53, 54, 55, 55, 58, 62, 62, 62, 63, 63, 63, 65, 65, 66, 66, 68, 69, 71, 72, 72, 72, 76, 76, 76, 77, 79, 79, 79, 80, 80, 82, 84, 85, 86, 88, 88, 89, 90, 92, 92, 93, 95, 95, 96, 97, 97, 98, 99, 99, 100]

```python
sum([i for i in range(101)])
```

    5050

```python
D = dict(enumerate(L1))
```

```python
type(D), type(L1), type(tuple(L1))
```

    (dict, list, tuple)

```python
print(D, end ='')
```

    {0: 1, 1: 2, 2: 4, 3: 5, 4: 6, 5: 7, 6: 9, 7: 10, 8: 11, 9: 13, 10: 13, 11: 14, 12: 16, 13: 17, 14: 17, 15: 17, 16: 18, 17: 18, 18: 18, 19: 19, 20: 19, 21: 21, 22: 23, 23: 23, 24: 23, 25: 27, 26: 30, 27: 30, 28: 31, 29: 35, 30: 37, 31: 37, 32: 38, 33: 38, 34: 39, 35: 39, 36: 40, 37: 41, 38: 43, 39: 44, 40: 44, 41: 45, 42: 45, 43: 46, 44: 47, 45: 48, 46: 48, 47: 49, 48: 49, 49: 50, 50: 53, 51: 54, 52: 55, 53: 55, 54: 58, 55: 62, 56: 62, 57: 62, 58: 63, 59: 63, 60: 63, 61: 65, 62: 65, 63: 66, 64: 66, 65: 68, 66: 69, 67: 71, 68: 72, 69: 72, 70: 72, 71: 76, 72: 76, 73: 76, 74: 77, 75: 79, 76: 79, 77: 79, 78: 80, 79: 80, 80: 82, 81: 84, 82: 85, 83: 86, 84: 88, 85: 88, 86: 89, 87: 90, 88: 92, 89: 92, 90: 93, 91: 95, 92: 95, 93: 96, 94: 97, 95: 97, 96: 98, 97: 99, 98: 99, 99: 100}

```python
sum(D) == (0+99)*100/2
```

    True

### any函数所作用的对象中只要有一项的布尔值为True就返回True

```python
any(['',''])
```

    False

```python
all(['spam','','ni'])
```

    False

```python
any?
```

    Signature: any(iterable, /)
    Docstring:
    Return True if bool(x) is True for any x in the iterable.

    If the iterable is empty, return False.
    Type:      builtin_function_or_method

```python
S = 'python'
L = []
for i in S:
    L.append(i)
```

```python
L
```

    ['p', 'y', 't', 'h', 'o', 'n']

```python
max(L)
```

    'y'

```python
min(L)
```

    'h'

```python
for i in L:
    print('%s = ' % i + str(ord(i)))
```

    p = 112
    y = 121
    t = 116
    h = 104
    o = 111
    n = 110

```python
max(['A','a'])
```

    'a'

```python
print(ord('A'), ord('a'))
```

    65 97

### 52个英文字母(包含大小写) + 键盘上的其他按键都对应一个ASCII码

```python
bin(65), hex(65), oct(65)
```

    ('0b1000001', '0x41', '0o101')

```python
print(ord('x'), ord('='), ord('2'), ord('\n'),ord('x')+ord('=')+ord('2')+ord('\n') )
```

    120 61 50 10 241

```python
S = 'import sys\n'
list((i for i in S))
```

    ['i', 'm', 'p', 'o', 'r', 't', ' ', 's', 'y', 's', '\n']

```python
print([ord(i) for i in list((i for i in S))])
```

    [105, 109, 112, 111, 114, 116, 32, 115, 121, 115, 10]

```python
f = open('script1.py', mode='w')
```

```python
f.write('import sys\n')
f.write('print(sys.path)\n')
f.write('x = 2\n')
f.write('print(2**33)\n')
```

    13

```python
f.close()
```

```python
f = open('script1.py', 'r')
```

```python
f.read()
```

    'import sys\nprint(sys.path)\nx = 2\nprint(2**33)\n'

```python
f.close()
```

```python
# %load script1.py
import sys
print(sys.path)
x = 2
print(2**33)
```

```python
max(open('script1.py'))
```

    'x = 2\n'

```python
ord('i'), ord('p'), ord('x')
```

    (105, 112, 120)

```python
L1 = list(range(1,101,1))
```

```python
L2 = []
for i in L1:
    L2.append(str(i))
```

```python
S = '+'.join(L2)
```

```python
type(L1[0])
```

    int

```python
eval(S)
```

    5050

```python
S
```

    '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+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100'

```python
import functools, operator
functools.reduce(operator.add, L1)
```

    5050

```python
print(L1, end='')
print('\n')
print(L2, end='')
```

    [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, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

    ['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', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']

### Sympy 完全是python写的，并不像看起来的那样上流

```python
from sympy import *
init_session()
```

    IPython console for SymPy 1.4 (Python 3.7.4-64-bit) (ground types: python)

    These commands were executed:
    >>> from __future__ import division
    >>> from sympy import *
    >>> x, y, z, t = symbols('x y z t')
    >>> k, m, n = symbols('k m n', integer=True)
    >>> f, g, h = symbols('f g h', cls=Function)
    >>> init_printing()

    Documentation can be found at https://docs.sympy.org/1.4/

```python
Eq(Sum(n,(n,1,100)), Sum(n,(n,1,100)).doit())
```

```python
Eq(Product(n, (n,1,100)), Product(n, (n,1,100)).doit())
```

```python
factorial(100)
```

```python
L1 = list(range(1,101,1))
functools.reduce(operator.add, L1)
```

```python
L1 = list(range(1,101,1))
I = functools.reduce(operator.mul, L1)
```

```python
I
```

```python
# %load script1.py
import sys
print(sys.path)
x = 2
print(2**33)
```

```python
list(open('script1.py'))
```

    ['import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(2**33)']

```python
tuple(open('script1.py'))
```

    ('import sys\n', 'print(sys.path)\n', 'x = 2\n', 'print(2**33)')

```python
a, b, c, d= open('script1.py')
```

```python
a, d
```

    ('import sys\n', 'print(2**33)')

```python
a, *b = open('script1.py')
```

```python
type(a), type(b)
```

    (str, list)

```python
print(a); print('\n'); print(b)
```

    import sys

    ['print(sys.path)\n', 'x = 2\n', 'print(2**33)']

```python
set(open('script1.py'))
```

    {'import sys\n', 'print(2**33)', 'print(sys.path)\n', 'x = 2\n'}

```python
set?
```

    Init signature: set(self, /, *args, **kwargs)
    Docstring:
    set() -> new empty set object
    set(iterable) -> new set object

    Build an unordered collection of unique elements.
    Type:           type
    Subclasses:     AssumptionsContext

```python
set()
```

```python
L1
```

```python
print(set(L2)) #对于字符串来说，它返回的是无序的
```

    {'20', '61', '4', '38', '40', '26', '78', '93', '46', '64', '35', '56', '85', '12', '36', '57', '86', '7', '90', '91', '5', '69', '54', '25', '74', '62', '75', '39', '60', '28', '8', '16', '47', '23', '34', '88', '37', '63', '18', '10', '13', '41', '79', '100', '52', '65', '99', '32', '72', '45', '98', '89', '76', '1', '96', '67', '59', '77', '95', '84', '24', '11', '27', '81', '2', '66', '9', '29', '6', '97', '83', '22', '92', '44', '31', '82', '68', '30', '55', '33', '73', '3', '42', '19', '58', '15', '94', '70', '53', '51', '14', '21', '71', '80', '48', '17', '43', '87', '50', '49'}

```python
print(set(L1)) #对于整数来说，它返回的是有序的
```

    {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, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}

### 创造的是一个无序的元素独一无二的集合，而且作用于不同的对象的话，得到的结果也是不一样的

```python
set('asafgjasa')  # 字符串
```

    {'a', 'f', 'g', 'j', 's'}

```python
D = dict(enumerate(L2))
```

```python
set(D) # set它把字典当中的关键词提取出来，创造新的集合
```

```python
D2 = {i : i for i in L2}
```

```python
print(set(D2),end='')
```

    {'76', '20', '1', '61', '96', '4', '59', '38', '40', '67', '77', '84', '95', '24', '26', '78', '93', '11', '46', '27', '64', '81', '2', '66', '9', '29', '6', '97', '83', '35', '56', '85', '12', '22', '92', '36', '44', '57', '86', '7', '31', '90', '91', '5', '82', '68', '30', '69', '54', '25', '74', '55', '33', '62', '75', '39', '73', '60', '3', '28', '42', '8', '16', '47', '23', '19', '34', '58', '88', '15', '37', '94', '63', '70', '53', '18', '10', '51', '14', '21', '71', '13', '41', '80', '79', '100', '48', '52', '65', '99', '17', '43', '32', '87', '72', '45', '50', '49', '98', '89'}

```python
print(set(set(D2))) # set为什么返回的结果与预想不一样
```

    {'76', '20', '1', '61', '96', '4', '59', '38', '40', '67', '77', '84', '95', '24', '26', '78', '93', '11', '46', '27', '64', '81', '2', '66', '9', '29', '6', '97', '83', '35', '56', '85', '12', '22', '92', '36', '44', '57', '86', '7', '31', '90', '91', '5', '82', '68', '30', '69', '54', '25', '74', '55', '33', '62', '75', '39', '73', '60', '3', '28', '42', '8', '16', '47', '23', '19', '34', '58', '88', '15', '37', '94', '63', '70', '53', '18', '10', '51', '14', '21', '71', '13', '41', '80', '79', '100', '48', '52', '65', '99', '17', '43', '32', '87', '72', '45', '50', '49', '98', '89'}

```python
print(set(tuple(L2))) # 元组
```

    {'20', '61', '4', '38', '40', '26', '78', '93', '46', '64', '35', '56', '85', '12', '36', '57', '86', '7', '90', '91', '5', '69', '54', '25', '74', '62', '75', '39', '60', '28', '8', '16', '47', '23', '34', '88', '37', '63', '18', '10', '13', '41', '79', '100', '52', '65', '99', '32', '72', '45', '98', '89', '76', '1', '96', '67', '59', '77', '95', '84', '24', '11', '27', '81', '2', '66', '9', '29', '6', '97', '83', '22', '92', '44', '31', '82', '68', '30', '55', '33', '73', '3', '42', '19', '58', '15', '94', '70', '53', '51', '14', '21', '71', '80', '48', '17', '43', '87', '50', '49'}

```python
print(set("""Strictly speaking, the max and min functions can be applied to files as well—they automatically use the iteration protocol to scan the file and pick out the lines with the highest
and lowest string values, respectively though I’ll leave valid use cases to your
imagination"""), end='')
```

    {'m', 'a', 'e', 's', 'o', 'p', 'h', 'r', ' ', '\n', 'v', 'u', ',', 'c', 'g', 'b', '—', 'l', 'n', '’', 'f', 'd', 't', 'I', 'S', 'x', 'i', 'k', 'y', 'w'}

```python
print(set("""石正丽等中国科学家发现：进化的“军备竞赛”（arms race）塑造了病毒及其受体的多样性。

鉴定涉及种间传播的关键残基对于预测潜在的病原体、了解病毒如何从野生动物向人类跃迁，非常重要。

以前，研究者已经在中华菊头蝠中鉴定出具有不同遗传特征的SARS相关冠状病毒（SARSr-CoV）。而这份最新研究还展现了中华菊头蝠种群中蝙蝠受体ACE2（血管紧张素转化酶2）的高度多样性。这些ACE2变体支持SARS病毒和SARS相关冠状病毒的感染，但对不同刺突蛋白具有不同的结合亲和力。

SARS相关冠状病毒刺突蛋白对人ACE2拥有更高结合亲和力，显示这些病毒具有向人类跃迁传染的能力。ACE2和SARS相关冠状病毒刺突蛋白之间的界面处残基的正向选择，表明它们之间存在长期和持续的协同进化动力学。因此，持续监视蝙蝠中的这一组病毒对于预防下一个SARS样疾病非常必要。

以上研究来自中科院武汉病毒所石正丽团队与福建师范大学生命科学学院欧阳松应教授在预印本平台 bioRxiv 上发表的论文：Evolutionary arms race between virus and host drives genetic diversity in bat SARS related coronavirus spike genes。

中华菊头蝠是SARS病毒的宿主，其体内还携带多种SARS相关冠状病毒。这些病毒具有高度的遗传多样性，尤其是病毒的刺突蛋白基因。尽管有着不同程度的变异，一些蝙蝠SARS相关冠状病毒仍可以利用人类受体ACE2进入人体细胞。研究者推测，蝙蝠的ACE2受体和SARS相关冠状病毒刺突蛋白之间，有着相互作用，而这驱动了SARS相关冠状病毒的遗传多样性。

研究者鉴定出了一系列中华菊头蝠ACE2变异体，这些变异体中有一些与SARS-CoV刺突蛋白有相互作用的多态位点。携带不同刺突蛋白的伪病毒或SARS相关冠状病毒，在表达了蝙蝠ACE2变体的细胞中有着不同的瞬时感染效率。通过测定SARS病毒、SARS相关冠状病毒刺突蛋白与蝙蝠受体、人类受体分子之间的结合亲和力，能观察到相关的结果。

所有被测试的蝙蝠SARS相关冠状病毒刺突蛋白与人ACE2的结合亲和力，均高于其对蝙蝠ACE2的结合亲和力。不过SARS相关冠状病毒刺突蛋白与人ACE2的结合亲和力，比SARS-CoV刺突蛋白与人ACE的亲和力低10倍。

结构建模表明，刺突和ACE2之间的结合亲和力差异可能是由于这两个分子界面中某些关键残基的改变而引起。分子进化分析表明，这些残基处于强的正选择。

这些结果表明SARS新冠病毒刺突蛋白和蝙蝠ACE2可能随着时间的推移而互相进化，并经历彼此的选择压力，从而触发了进化的“军备竞赛”动力学。这进一步证明了，中华菊头蝠是SARS相关冠状病毒的天然宿主。

冠状病毒是包膜病毒，包含单股正链RNA。该亚科有四个属，即α、β、γ和δ。α冠状病毒和β冠状病毒起源于蝙蝠或啮齿动物，而γ冠状病毒和δ冠状病毒起源于鸟类。自21世纪初以来，三种β型冠状病毒已引起人类严重肺炎暴发。分别是SARS-CoV，MERS-CoV和SARS-CoV-2。

SARS-CoV-2引发的疫情使人们回想起17年前发生的SARS疫情。SARS是一种人畜共患病，在接下来的几年中，科学家从中国和欧洲不同地区的蝙蝠中检测或分离出了具有不同遗传特征的75种SARS相关冠状病毒（SARSr-CoV）。

蝙蝠SARS相关冠状病毒与人类和果子狸的SARS-CoVs有96％的核苷酸序列相似度，其中可变区最多的是刺突蛋白（S）和辅助蛋白ORF3和ORF8。此外，研究者已经确定了不同蝙蝠SARS相关冠状病毒基因组中能找到SARS-CoV的所有基因构建基块，这表明SARS病毒的祖先是通过蝙蝠SARS相关冠状病毒基因组的重组而来，其起源于蝙蝠。

病毒感染的第一步是识别细胞受体，这也是必不可少的步骤。冠状病毒的进入是由病毒刺突蛋白（Spike，S）和细胞表面受体之间的特异性相互作用介导，然后病毒与宿主膜之间发生融合。冠状病毒刺突蛋白在功能上分为两个亚基：细胞附着亚基（S1）和膜融合亚基（S2）。 S1区域包含N端结构域（NTD）和C端结构域（CTD）；两者均可用于冠状病毒受体结合（RBD）。

对于SARS-CoV，其S1-CTD作为RBD与细胞的受体即血管紧张素转换酶2（ACE2）结合。冷冻电镜和晶体结构分析，确定了SARS病毒的S-RBD与人ACE2之间界面中的一些关键残基。

根据S蛋白的大小，蝙蝠SARS相关冠状病毒可以分为两个不同的进化枝。进化枝1包含病毒具有与SARS病毒大小相同的刺突蛋白。而由于5、12或13个氨基酸缺失，属于进化枝2的病毒其刺突蛋白则比SARS病毒的小。

尽管RBD有所不同，所有进化枝1毒株都可以使用ACE2进入细胞，而进化枝2毒株则由于上述缺失无法直接进入。这些结果表明，就基因组相似性和ACE2的使用而言，进化枝1的成员很可能是SARS病毒的直接来源。

ACE2在功能上分为两个结构域：N末端结构域参与SARS-CoV结合，C末端结构域参与心功能的调节。先前的结果表明，不同来源的ACE2的C末端结构域相对保守，而N末端结构域在物种间显示出更多的多样性。此前已证明SARS病毒可以利用水鼠耳蝠的ACE2和中华菊头蝠的ACE2。RBD结合位点中的微小突变，可将ACE2从对SARS-CoV结合不易感转变为易感。由于属于进化枝1的所有SARS相关冠状病毒都可从中华菊头蝠体内提取出来，而且也都可以利用ACE2，因此研究者提出问题：中华菊头蝠ACE2中的变异是否可能有导致了蝙蝠SARS相关冠状病毒的多样性。

研究团队研究了中华菊头蝠ACE2基因的多态性，并通过分子进化分析，蛋白质亲和力测定和病毒感染测定相结合，评估了它们对不同蝙蝠SARS相关冠状病毒刺突蛋白的敏感性和结合亲和力。

结果表明，SARS相关冠状病毒的刺突蛋白多样性可能会受到中华菊头蝠ACE2变体的自然选择压力； 在长期共存期间，SARSr-CoV刺突蛋白可能会被中华菊头蝠的ACE2选择，以维持自身遗传多样性并适合中华菊头蝠的种群。

ACE2基因在中华菊头蝠种群中表现出高度多态性

根据蝙蝠SARS相关冠状病毒的流行情况以及样品组织的可用性和质量，研究者使用来自三个省（湖北，广东和云南）的样品进行ACE2扩增。

除了团队先前测序过的蝙蝠ACE2（分别从湖北，广西和云南收集的样本ID 832、411和3357）和其他蝙蝠ACE2（GenBank登记号ACT66275，这是从香港收集的样本）外，研究者从21只中华菊头蝠蝠个体中获得了ACE2基因序列：湖北有5个，广东有9个，云南有7个。这些蝙蝠ACE2序列在其物种内显示98-100％的氨基酸同一性，与人ACE2的显示80-81％的氨基酸同一性。

这些蝙蝠ACE2在N端区域观察到了主要变化，包括一些先前已确定与SARS病毒的 S-RBD接触的残基。根据非同义SNP分析鉴定出8个残基，包括24、27、31、34、35、38.41和42。这8个残基的组合产生了8个等位基因，包括RIESEDYK，LIEFENYQ，RTESENYQ，RIKSEDYQ，QIKSEDYQ， RMTSEDYQ，EMKT KDHQ和EIKT EIKTKDHQ，分别命名为等位基因1-8。

除了先前研究（等位基因4、7和8）中的ACE2基因型数据外，研究者在中华菊头蝠种群中还鉴定出5个新的等位基因。“等位基因2”在两个省的样本中有发现，“等位基因4”在3个省中有发现，而其他等位基因似乎在地理上受到限制。总之，在广东发现了3个等位基因（4、6和8），云南发现了4个等位基因（1、2、4和7），在湖北发现了3个等位基因（2、4和5），在广西和香港分别找到了1个等位基因。在发现SARS病毒直接祖先的云南一蝙蝠洞中，研究者发现了4个等位基因共存。

综上所述，这些数据表明ACE2变异体已经在不同地区的中华菊头蝠种群中长期存在。与SARS病毒的S-RBD直接接触的位点的取代，表明它们在SARS病毒的进化和传播过程中可能具有重要功能。"""), end ='')
```

    {'M', 'F', '还', '：', '北', '病', '似', 'R', '能', '界', '来', '触', '广', '畜', 'v', '源', '别', '究', '本', '石', '瞬', '含', 'l', '人', '离', '7', '丽', '四', '齿', '镜', '辅', '何', '功', '物', '鉴', '有', '暴', '枝', 'r', '疾', '野', '监', '将', '如', '构', 'K', 'd', '残', '根', '起', '织', '冠', '出', 'm', '酸', '水', '1', '心', '染', '鸟', '平', '均', '改', 'p', '适', '拥', '大', '2', '9', '属', '低', '续', '选', '三', '附', '以', '携', '介', '彼', '移', '提', '亲', 'E', '想', '历', '啮', '文', '胞', '建', '或', '天', '松', 'o', 'h', '晶', '其', '等', 'C', 'b', '征', '小', '类', '列', '重', '.', '宿', '苷', '增', '处', 'I', '结', '析', '面', '取', '研', '主', '团', '致', '台', '；', '述', '都', 'u', 'B', '炎', '此', '显', '名', '时', '所', '第', '即', '赛', '察', '必', '塑', '明', '血', '进', '欧', '论', '就', '8', '制', '守', '）', '具', '导', '股', 'γ', '否', '转', '序', '耳', 'D', '毒', '参', 'N', '观', '是', '膜', 'P', '共', '突', '因', '院', 't', '防', '之', '管', '肺', '号', '而', '状', '助', '据', '达', '世', '随', '竞', '记', '6', '经', '不', 'A', 'L', 'T', '点', '阳', '疫', '协', '除', '末', '尤', '比', '造', '分', '蝙', '两', '。', 'x', '关', 'i', '祖', '端', '仍', '-', '几', '3', '换', '产', '”', '体', '紧', '初', '长', '测', '鼠', '则', '先', '乎', '择', '着', '省', '云', '对', '伪', '特', '迁', '它', '患', '个', '回', '们', '由', '尽', '问', '得', '样', 'a', '酶', '入', '命', '性', '用', '华', '狸', '化', '确', '这', '期', '已', '找', '情', '些', '东', '成', '只', '0', '自', '很', '收', '他', '应', '单', '遗', '识', '冷', '差', '然', '，', '种', '融', '存', '某', '模', '步', '及', '视', '中', '印', '块', '香', '合', 'δ', '持', '行', '基', '包', '电', '无', '于', '最', '链', '利', '外', '品', '义', '在', '区', '支', ' ', '题', '总', '张', '后', '失', '言', '保', '预', '上', '感', '受', '位', '到', '刺', '国', '检', '评', '向', '驱', '纪', '表', '度', '播', '同', '新', '了', '展', '生', '非', '群', '范', '示', 'S', '与', '流', '更', '扩', '使', '骤', '质', '年', '（', '程', '原', '倍', '蛋', '现', '“', '敏', '键', 'c', '会', '节', '军', '少', '理', '接', '湖', '可', '作', 'V', '试', '综', '港', '该', '和', '白', '缺', '互', '过', '域', '引', '4', '为', '维', '调', '\n', '异', '潜', '队', 'n', '压', '也', 'Q', '系', '数', '法', '推', '5', 'H', '％', '率', '解', 'w', '、', '跃', '核', '要', 'G', '的', '通', '菊', '头', 'e', '但', '株', '并', '洞', '细', '集', '氨', '前', '果', '内', '亚', '师', '直', '易', '括', '估', '家', '强', '南', '员', '下', '福', '严', '份', '量', '登', '组', '传', '间', '子', '地', '力', 's', '正', '效', '代', '洲', '身', 'O', '动', '备', 'Y', '一', '武', '况', '高', '态', '变', '被', '西', '发', '者', '带', 'α', '获', '限', '授', '证', 'g', '型', '蝠', '且', '冻', '相', '科', '学', '常', '素', '定', '教', 'β', '多', '微', '从', '汉', 'k', 'y', '涉'}

```python
{ line for line in open('script1.py')}
```

    {'import sys\n', 'print(2**33)', 'print(sys.path)\n', 'x = 2\n'}

```python
ord('i'), ord('p'), ord('x')
```

```python
# %load script1.py
import sys
print(sys.path)
x = 2
print(2**33)
```

```python
ord('7'), ord('2')
```

```python
{ix: line for ix, line in enumerate(open('script1.py'))}
```

    {0: 'import sys\n', 1: 'print(sys.path)\n', 2: 'x = 2\n', 3: 'print(2**33)'}

```python
{line for line in open('script1.py') if line[0] == 'p'}
```

    {'print(2**33)', 'print(sys.path)\n'}

```python
{ix: line for (ix, line) in enumerate(open('script1.py'))}
```

    {0: 'import sys\n', 1: 'print(sys.path)\n', 2: 'x = 2\n', 3: 'print(2**33)'}

```python
ord('s') # 函数
```

```python
def f(a, b,c, d):print(a,b,c,d,sep=',')
```

```python
f(1,2,3,4)
```

    1,2,3,4

```python
f(*[1,2,3,45]) # a, b, c, d是单个参数
```

    1,2,3,45

```python
a, *b = open('script1.py')
```

```python
b
```

    ['print(sys.path)\n', 'x = 2\n', 'print(2**33)']

```python
def f(a,b,c,d): print(a*2, b*3, c*4, d*5, end='\n' )
```

```python
f(*open('script1.py'))
```

    import sys
    import sys
     print(sys.path)
    print(sys.path)
    print(sys.path)
     x = 2
    x = 2
    x = 2
    x = 2
     print(2**33)print(2**33)print(2**33)print(2**33)print(2**33)

```python
# %load script1.py
import sys
print(sys.path)
x = 2
print(2**33)
```

```python
X = (1,2)
Y = (3,4)
zip(X,Y)
```

    <zip at 0x20490a0a788>

```python
tuple(zip(X,Y)); list(zip(X,Y))
```

```python
zip(zip(X,Y))
```

    <zip at 0x2048f0d7808>

```python
A, B = zip(*zip(X,Y))
```

```python
print(A, end='\n'); print(B, end='\n')
```

    (1, 2)
    (3, 4)

```python
C, D = zip(X,Y) # X = (1,2) Y = (3,4)
```

```python
print(C, end='\n'); print(D, end='\n')
```

    (1, 3)
    (2, 4)

```python
A, B = zip(C,D)
```

```python
A, B = zip(zip(X,Y)) #
```

```python
print(A, end='\n'); print(B, end='\n')
```

    ((1, 3),)
    ((2, 4),)

```python
A, B = zip(X,Y)
C = A, B
```

```python
C
```

```python
E, F= zip(C,)
```

```python
print(E, end='\n'); print(F, end='\n')
```

    ((1, 3),)
    ((2, 4),)

##### 什么叫字典视图对象？

### Python3.0中的新的可迭代对象

Python 3 的版本比Python2.x 更加强调迭代

```python
zip('abc','xyz')  # 在Python3.x中返回的是可迭代的对象，而在2.x版本中返回是一个列表
```

    <zip at 0x204909cf908>

```python
list(zip('abc','xyz'))
```

    [('a', 'x'), ('b', 'y'), ('c', 'z')]

### range迭代器

```python
R = range(10)
R
```

    range(0, 10)

```python
I = iter(R)
next(I)
```

    0

```python
next(I), next(I), next(I), next(I), next(I), next(I), next(I)
```

    (1, 2, 3, 4, 5, 6, 7)

### range 对象只支持迭代，索引，长度函数，它们不支持其他的序列操作

```python
len(R), R[0], R[-1], next(I), I.__next__()
```

    (10, 0, 9, 8, 9)

#### 版本偏差，xrange, file.xreadlines() 只适用于python 2.x; range和open在python 3.x取而代之

```python
range(10), map(list(range(10)), list(range(10,20))), zip(list(range(10)),list(range(10,20))), filter(bool, open('script1.py'))
```

    (range(0, 10),
     <map at 0x132246edf88>,
     <zip at 0x13224512fc8>,
     <filter at 0x13222875388>)

```python
f = open('script1.py')
```

```python
f is iter(f)
```

    True

```python
R = range(3); M = map(abs, list(range(3,6))); Z = zip(list(range(3)),list(range(3,6))); F = filter(bool, open('script1.py'))
```

```python
R is iter(R), M is iter(M), Z is iter(Z), F is iter(F)
```

    (False, True, True, True)

#### 除了range, map和zip,以及filter都是自身的迭代器（它们在一次遍历之后，就不能在进行访问了）

```python
f.read()
```

    'import sys\nprint(sys.path)\nx = 2\nprint(2**33)'

```python
f.read() # 一次迭代完全后，它们将会迭代完全
```

    ''

```python
list(map(abs,(-1,0,1)))
```

    [1, 0, 1]

```python
Z = zip((1,2,3),(10,20,30))
```

```python
print('%s ！= ' % str(next(Z)), next(Z))
```

    (1, 10) ！=  (2, 20)

```python
next(Z), next(Z), next(Z)
```

    ((1, 10), (2, 20), (3, 30))

### map,以及zip还有filter都是一次性迭代器，像文件迭代器一样，如果一次性遍历完之后,就会给出停止迭代的错误，

```python
for pair in Z: print(pair)
```

```python
Z = zip((1,2,3),(10,20,30))
for pair in Z: print(pair)
```

    (1, 10)
    (2, 20)
    (3, 30)

```python
for pair in Z: print(pair)
```

```python
def f(x):
    if bool(x) == False:
        return x
    else:
        pass

list(filter(f,['spam','','ni']))
```

    []

```python
type(False)
```

    bool

```python
list('')
```

    []

```python
list(filter(bool,['spam','','ni']))
```

    ['spam', 'ni']

#### filter, map, zip它们既可以处理可迭代对象，也可以产生一个可迭代对象
#### range, 字典视图对象不能处理可迭代对象，但是可以产生一个可迭代对象

```python
range(1,101,2)
```

    range(1, 101, 2)

```python
list(range(1,101,2))
```

    [1,
     3,
     5,
     7,
     9,
     11,
     13,
     15,
     17,
     19,
     21,
     23,
     25,
     27,
     29,
     31,
     33,
     35,
     37,
     39,
     41,
     43,
     45,
     47,
     49,
     51,
     53,
     55,
     57,
     59,
     61,
     63,
     65,
     67,
     69,
     71,
     73,
     75,
     77,
     79,
     81,
     83,
     85,
     87,
     89,
     91,
     93,
     95,
     97,
     99]

### 多个迭代器 vs 单个迭代器

```python
R = range(3)
R is iter(R)
```

    False

```python
Z = zip((1,2,3),(10,12,13))
I1 = iter(Z)
I2 = iter(Z)
```

```python
Z is iter(Z), I1 is Z, I2 is Z
```

    (True, True, True)

```python
next(I1), next(I1), next(I2)
```

    ((1, 10), (2, 12), (3, 13))

```python
M = map(abs, (-1,0,1))
I1 = iter(M); I2 = iter(M)
print(next(I1),next(I2),next(I1))
# next(I2)
```

    1 0 1

```python
R = range(3)
I1, I2 = iter(R), iter(R)
```

```python
R is iter(R), I1 is R, I2 is R
```

    (False, False, False)

```python
[next(I1), next(I2), next(I1)]
```

    [0, 0, 1]

```python
class Text():
    """
    This is just an experiment performed for iterations related to classes
    """
    def PLUS(x,y):
        return str(x)+str(y)
    """
    PLUS can be used to convert two items to strings and add them together, and return the result.
    """
    def SUBSTR(x,y):
        return x[:y]
```

```python
Text.PLUS(1,2)
```

    '12'

```python
Text.SUBSTR('asahfjasfhajfjah',4)
```

    'asah'

```python
Text.PLUS(5,6789)
```

    '56789'

### 文件，字典以及字典的方法(keys,values,items) 都和range,map,zip,filter这些函数一样都会返回可迭代对象

```python
S = """As we saw briefly in Chapter 8, in Python 3.0 the dictionary keys, values, and items
methods return iterable view objects that generate result items one at a time, instead
of producing result lists all at once in memory. View items maintain the same physical
ordering as that of the dictionary and reflect changes made to the underlying dictionary.
Now that we know more about iterators, here’s the rest of the story:"""
```

```python
D = dict(enumerate(S))
```

```python
print(list(D.keys()), end='')
```

    [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, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416]

```python
I = iter(D)
```

```python
next(I), next(I), next(I), next(I), next(I)
```

    (0, 1, 2, 3, 4)

```python
for key in D.keys(): print(key,end=' ')
print('\n')
for key in D: print(key, end=' ')
```

    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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

    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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

```python
import numpy as np
D = dict(a=1,c=3,b=3)
print(D)
D = {'a': 1, 'c': 3, 'b': 2}
print(D)
D = { s : int(i) for s, i in zip('acb', '132')}
print(D)
```

    {'a': 1, 'c': 3, 'b': 3}
    {'a': 1, 'c': 3, 'b': 2}
    {'a': 1, 'c': 3, 'b': 2}

```python
D = {}
for i in [1,2,3]:
    for s in 'abc':
        D[s] = i
```

```python
D
```

    {'a': 3, 'b': 3, 'c': 3}

```python
for k in D: print(k, D[k], end=' ') #并不按照ASCII的顺序
```

    a 1 c 3 b 2

```python
for  k in sorted(D.keys()): print(k,D[k], end=' ')
for k in sorted(D): print(k, D[k], end= ' ')
```

    a 1 b 2 c 3 a 1 b 2 c 3

```python
help(Text)
```

    Help on class Text in module __main__:

    class Text(builtins.object)
     |  This is just an experiment performed for iterations related to classes
     |
     |  Methods defined here:
     |
     |  PLUS(x, y)
     |
     |  SUBSTR(x, y)
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)

```python

```

Chapter 14 Iterations and Comprehensions (2).ipynb