计算机科学和Python编程导论week7

这一章听的不是很懂,主要还是平时可能用到的地方不多,网上看了一个例子,感觉还不错。一棵树由一系列结点和一系列连接结点的边组成。由列表表示的树如下:

In [35]: def binary_tree(r):
   ...:     return [r, [], []]
   ...: def insert_left(root, new_branch):
   ...:     t = root.pop(1)   # The left child position
   ...:     if len(t) > 1:   # if not empty
   ...:         # The origin left child turn to be the left child of new_branch
   ...:         root.insert(1, [new_branch, t, []])
   ...:     else:
   ...:         root.insert(1, [new_branch, [], []])
   ...:     return root
   ...: def insert_right(root, new_branch):
   ...:     t = root.pop(2)
   ...:     if len(t) > 1:
   ...:         root.insert(2, [new_branch, [], t])
   ...:     else:
   ...:         root.insert(2, [new_branch, [], []])
   ...:     return root
   ...: def get_root_val(root):
   ...:     return root[0]
   ...: def set_root_val(root, new_val):
   ...:     root[0] = new_val
   ...: def get_left_child(root):
   ...:     return root[1]
   ...: def get_right_child(root):
   ...:     return root[2]
   ...: 

In [36]: x = binary_tree('a')
   ...: insert_left(x,'b')
   ...: insert_right(x,'c')
   ...: insert_right(get_right_child(x), 'd')  # important!
   ...: insert_left(get_right_child(get_right_child(x)), 'e')
   ...: 
Out[36]: ['d', ['e', [], []], []]
绘图以及类的进一步扩展

这一章节讲的主要是pylab模块,而且讲的不够详细。而我平时接触到的更多的其实是matplotlib,具体是操作过程可以参见《利用Pyhon进行数据分析》以及,网络上的视频教程。
参考视频:
Python数据可视化分析 matplotlib教程
Matplotlib Python 画图教程 (莫烦Python)
Python数据可视化分析 matplotlib

书中的例子,手敲如下:

In [3]: import pylab

In [4]: pylab.figure(1)
   ...: pylab.plot([1,2,3,4],[1,7,3,5])
   ...: pylab.show()
   ...: 
pylab1.png
In [5]: pylab.figure(1)
   ...: pylab.plot([1,2,3,4], [1,2,3,4])
   ...: pylab.figure(2)
   ...: pylab.plot([1,4,2,3], [5,6,7,8])
   ...: pylab.savefig('Figure-Addie')
   ...: pylab.figure(1)
   ...: pylab.plot([5,6,10,3])
   ...: pylab.savefig('Figure-Jane')
   ...: 
Figure-Jane.png
figure-addie.png
In [7]: principal = 10000 #初始投资
   ...: interestRate = 0.05
   ...: years = 20
   ...: values = []
   ...: for i in range(years + 1):
   ...:     values.append(principal)
   ...:     principal += principal*interestRate
   ...: pylab.plot(values)
   ...: 
Out[7]: [<matplotlib.lines.Line2D at 0x7f6cf839c6d8>]
left.png
In [8]: principal = 10000 #初始投资
   ...: interestRate = 0.05
   ...: years = 20
   ...: values = []
   ...: for i in range(years + 1):
   ...:     values.append(principal)
   ...:     principal += principal*interestRate
   ...: pylab.plot(values)
   ...: pylab.title('5% Growth, Compounded Annually')
   ...: pylab.xlabel('Years of Compounding')
   ...: pylab.ylabel('Value of Principal ($)')
   ...: 
Out[8]: Text(0,0.5,'Value of Principal ($)')
right.png

关于《利用Python进行数据分析》第8章绘图和可视化复习

主要注意以下技巧点:
1、Figure和Subplot,其中Subplot表示子图的意思。
2、颜色、标记和线形。
3、刻度、标签和图例。
4、设置标题、轴标签、刻度以及刻度标签。
5、添加图例。
6、注解以及在Subplot上绘图。
7、文件的保存

一、导入相关包

In [23]: from pandas import Series,DataFrame
In [26]: import numpy as np
In [27]: import pandas as pd

二、线形图

In [28]: s = Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
In [30]: s.plot()
Out[30]: <matplotlib.axes._subplots.AxesSubplot at 0x7f6cf826bc18>
plot.png
In [32]: df = DataFrame(np.random.randn(10,4).cumsum(0),columns=['A','B','C','D'],
                      index = np.arange(0,100,10))

In [34]: df
Out[34]: 
           A         B         C         D
0  -0.989531 -2.115333  0.869333 -0.912592
10 -0.610439 -2.252472 -0.341660 -1.992918
20 -0.346735 -3.405280 -1.292019 -1.220195
30 -0.794386 -4.347492 -1.352773 -0.573720
40 -1.623164 -3.324624  0.539607  0.759043
50 -2.233892 -4.262740  1.181381 -0.548779
60 -4.365038 -1.676428  1.883277 -0.400880
70 -4.531204 -2.335836  1.182581 -0.463981
80 -5.393352 -2.627742 -0.540208 -1.420075
90 -5.502896 -3.457975 -0.003414 -0.820583

In [35]: df.plot()
Out[35]: <matplotlib.axes._subplots.AxesSubplot at 0x7f6ce99fe550>

plot1.png

三、柱状图

In [39]: df = DataFrame(abs(np.random.randn(6,4)),columns=pd.Index(['A','B','C','D']),
                    index = ['one','two','three','four','five','six'])   
#注意加个abs()函数,将柱状图方向一致

In [39]: 

In [40]: df
Out[40]: 
              A         B         C         D
one    0.551014  1.364315  0.371038  0.760380
two    2.105145  1.188208  0.624236  1.503707
three  0.229816  0.018687  0.686012  0.762051
four   1.142801  1.837860  0.179224  0.018175
five   0.068223  0.189362  0.373415  0.217577
six    0.107417  1.518513  0.162553  0.715304

In [41]: df.plot(kind = 'bar')
Out[41]: <matplotlib.axes._subplots.AxesSubplot at 0x7f6cf83ef940>
bar.png

四、散点图

In [45]: plt.scatter(np.random.randn(100),np.random.randn(100))
Out[45]: <matplotlib.collections.PathCollection at 0x7f6ce978c198>
scatter.png

作业试题:

Problem 4

def jumpAndBackpedal(isMyNumber):
    '''
    isMyNumber: Procedure that hides a secret number. 
     It takes as a parameter one number and returns:
     *  -1 if the number is less than the secret number
     *  0 if the number is equal to the secret number
     *  1 if the number is greater than the secret number
 
    returns: integer, the secret number
    ''' 
    guess = 1
    if isMyNumber(guess) == 0:
        return guess
    foundNumber = False
    while not foundNumber and isMyNumber(guess):
        sign = isMyNumber(guess)
        if sign == -1:
            guess *= 2
        else:
            guess -= 1
  return guess

# PROBLEM 7-1

def insert(atMe, newFrob):
    """
   atMe: a Frob that is part of a doubly linked list
   newFrob:  a Frob with no links 
   This procedure appropriately inserts newFrob into the linked list that atMe is a part of.    
   """
    # The new chain element has the same name of atMe
    if newFrob.name == atMe.name:
        newFrob.after = atMe.after
        atMe.after = newFrob
        newFrob.before = atMe
        # The new chain element has a next element
        if newFrob.after:
            newFrob.after.before = newFrob
   
    # The new element chain name comes before atMe's name
    elif newFrob.name < atMe.name:
        # atMe is the head of the chain
        if not atMe.before:
            atMe.before = newFrob
            newFrob.after = atMe           
        # atMe is not the head of the chain and its previous element equals newFrob    
        elif atMe.before and atMe.before == newFrob.before:
            newFrob.after = atMe
            atMe.before = newFrob
            newFrob.before.after = newFrob
        else:
            # "normal" case
            newFrob.after = atMe
            insert(atMe.before, newFrob)
    
    # The new element chain name comes after atMe's name          
    else:
        if atMe.after and atMe.after == newFrob.after:
            newFrob.before = atMe
            atMe.after = newFrob
            newFrob.after.before = newFrob
        elif atMe.after == None:
            atMe.after = newFrob
            newFrob.before = atMe
        else:
            newFrob.before = atMe
            insert(atMe.after, newFrob)

# PROBLEM 7-2

def findFront(start):
    """
   start: a Frob that is part of a doubly linked list
   returns: the Frob at the beginning of the linked list
   """
    if not start.getBefore():
        return start
    else:
return findFront(start.getBefore())
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354