2018-07-24

command 快捷键

  • ls: lists all files in the current directory
  • cd <path to directory>: change into the specified directory
  • mkdir <directory name>: make a new directory with the given name
  • mv <source path> <destination path>: move the file at the given source to the given destination

运行python file

  • Using no command-line options will run the code in the file you provide and return you to the command line.

    python3 lab00.py

  • -i: The -i option runs your Python script, then opens an interactive session. In an interactive session, you run Python code line by line and get immediate feedback instead of running an entire file all at once. To exit, type exit() into the interpreter prompt. You can also use the keyboard shortcut Ctrl-D on Linux/Mac machines or Ctrl-Z Enter on Windows.

    If you edit the Python file while running it interactively, you will need to exit and restart the interpreter in order for those changes to take effect.

    python3 -i lab00.py

  • -m doctest: Runs doctests in a particular file. Doctests are surrounded by triple quotes (""") within functions. Each test consists of >>> followed by some Python code and the expected output.

    python3 -m doctest lab00.py


An order of operation:

运算符 描述
** 指数 (最高优先级)
~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % // 乘,除,取模和取整除
+ - 加法减法
>> << 右移,左移运算符
& 位 'AND'
^ | 位运算符
<= < > >= 比较运算符
<> == != 等于运算符
= %= /= //= -= += *= **= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not 逻辑运算符
and 逻辑运算符
or 逻辑运算符

/ // %

True Division: / (decimal division)

Floor Division: // (integer division) 整数部分

Modulo: % (remainder)


return statement

When Python executes a return statement, the function terminates immediately.

A return statement completes the evaluation of a call expression and provides its value.

def what_prints():
    print('Hello World!')
    return 'Exiting this function.'
    print('61A is awesome!')
what_prints() 

Hello World!

'Exiting this function.'


when 28 means when True means always

positive = 28
while positive:
    print("positive?")
    positive -= 3

Result: Infinite Loop because positive never comes to 0


difference between return and print

return ‘hello’

‘hello’

print(‘hello’)

hello


a, b = b, a+b

>>> a = 1; b = 0
>>> a, b = b, a+b
>>> print(a, b)
>>> hello 
0 1
>>> a = 1; b = 0
>>> a = b
>>> b = a+b
>>> print(a, b)
0 0
>>> a = 1; b = 0
>>> a = b; b = a+b
>>> print(a, b)
0 0
>>> a = 1, b=2
File "<stdin>", line 1
SyntaxError: can't assign to literal

限制自变量:assert x > 0, 'x must be positive'

>>> def function_one(x):
...     assert x > 0, 'x must be positive'
...
>>> function_one(x=-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in function_one
AssertionError: x must be positive

编程可视化

tutor.composingprograms.com

http://pythontutor.com/composingprograms.html#mode=edit


make_test_dice

https://goo.gl/zesqCi

def make_test_dice(*outcomes):
    """
    Return a die that cycles deterministically through OUTCOMES.
    
    >>> dice = make_test_dice(1, 2, 3)
    >>> dice()
    1
    >>> dice()
    2
    >>> dice()
    3
    >>> dice()
    1
    >>> dice()
    2
 
    This function uses Python syntax/techniques not yet covered in this course.
    The best way to understand it is by reading the documentation and examples.
    """
    assert len(outcomes) > 0, 'You must supply outcomes to make_test_dice'
    for o in outcomes:
    assert type(o) == int and o >= 1, 'Outcome is not a positive integer'
    index = len(outcomes) - 1
    def dice():
        nonlocal index
        index = (index + 1) % len(outcomes)
        return outcomes[index]
    return dice

[score0, score1][0] 是值还是参数名?

score0 = 3
score1 = 5
[score0, score1][0] = 6 #the result shows that [score0, score1][0] means value of #0, not parameter
score0
>>> 3
score0 = 6 
score0
>>> 6

f2 嵌在 f1内,将f2中的x2的值赋给f1的变量

def announce_highest(who, previous_high=0, previous_score=0):
    """
    Return a commentary function that announces when WHO's score

    increases by more than ever before in the game.

    >>> f0 = announce_highest(1) # Only announce Player 1 score gains
    >>> f1 = f0(11, 0)
    >>> f2 = f1(11, 1)
    1 point! That's the biggest gain yet for Player 1
    >>> f3 = f2(20, 1)
    >>> f4 = f3(5, 20) # Player 1 gets 4 points, then Swine Swap applies
    19 points! That's the biggest gain yet for Player 1
    >>> f5 = f4(20, 40) # Player 0 gets 35 points, then Swine Swap applies
    20 points! That's the biggest gain yet for Player 1
    >>> f6 = f5(20, 55) # Player 1 gets 15 points; not enough for a new high
    """
    assert who == 0 or who == 1, 'The who argument should indicate a player.'
    # BEGIN PROBLEM 7
    "*** YOUR CODE HERE ***"
    def say1(score0, score1):
        diata = [score0, score1][who] - previous_score
        if diata > previous_high:
            if diata == 1:
                print("1 point! That's the biggest gain yet for Player", who)
            if diata != 1:
                print(diata, "points! That's the biggest gain yet for Player", who)
            return announce_highest(who, diata, [score0, score1][who])
        else:
            return announce_highest(who, previous_high, [score0, score1][who])
    return say1

  • [ ] # ?
def search(f):
    """Return the smallest non-negative integer x for which f(x) is a true value."""
    x = 0
    while True:
        if f(x):
            return x
        x += 1

def invert(f):
    """Return a function g(y) that returns x such that f(x) == y.

    >>> sqrt = invert(square)
    >>> sqrt(16)
    4
    """
    return lambda y: search(lambda x: f(x) == y)

def invert(f) --> define inver(f) --> input func f, return lambda y: , (parent = global)

lambda y: search() --> define lam(y) --> input y, return func search, (parent = invert)

search(lambda x: ) --> use search(f) --> input func lam(x), return x when lam(x) True, (parent = global)

lambda x: f(x) == y --> define lam(x) --> input x, return True or False, (parent = lam(y))


Q: When is the return expression of a lambda expression executed?

Choose the number of the correct choice:

  1. When you assign the lambda expression to a name.

you cannot assign a name to lambda expression

  1. When you pass the lambda expression into another function.

  2. When the function returned by the lambda expression is called.

  3. When the lambda expression is evaluated.

? 2


lambda z: print(z) returns Nothing!

>>> print_lambda = lambda z: print(z)
>>> print_lambda
? Function
-- OK! --

>>> one_thousand = print_lambda(1000)
? 1000
-- OK! --

>>> one_thousand
? 1000
-- Not quite. Try again! --

? Function
-- Not quite. Try again! --

? Error
-- Not quite. Try again! --

? Nothing
-- OK! --

Draw environment diagram

n = 9
def make_adder(n):
    return lambda k: k + n
add_ten = make_adder(n+1)
result = add_ten(n)

My environment diagram answer

global frame:

​ n [9]

​ make_adder ------> func make_adder(n) (parent = global)

​ λ ------> func λ(k) (parent = global)

​ add_ten ------> func λ(k) (parent = f1) (lambda k: k + 10)

​ result [19]

f1 make_adder(n+1) (parent = global):

​ n [10]

​ retur value: func λ

f2 add_ten λ(k) (parent = f1):

​ k [9]

​ return value: 19


如何判断函数的执行效率: Use cProfile.run()

def cycle01(f1, f2, f3):
    def g1(n):
        def g2(x):
            round = n // 3
            left_round = n % 3
            i = 1
            while i <= round:
                x = f3(f2(f1(x)))
                i = i+1
            if left_round == 0:
                return x
            elif left_round == 1:
                return f1(x)
            elif left_round == 2:
                return f2(f1(x))
        return g2
    return g1

def cycle02(f1, f2, f3):
    def g1(n):
        def g2(x):
            i = 1
            while i <= n:
                if i <= n:
                    x = f1(x)
                    i += 1
                else:
                    return x
                if i <= n:
                    x = f2(x)
                    i += 1
                else:
                    return x
                if i <= n:
                    x = f3(x)
                    i += 1
                else:
                    return x
            return x
        return g2
    return g1


import cProfile
import re
cProfile.run("cycle01(lambda x: x+4, lambda x: x+6, lambda x: x+9)(10000000)(4)")
cProfile.run("cycle02(lambda x: x+4, lambda x: x+6, lambda x: x+9)(10000000)(4)")
""""""

输出结果

PS E:\沐沐\Cousera\cs61a\lab\lab02> python E:\沐沐\Cousera\cs61a\run04.py
         3333339 function calls in 5.530 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  3333333    0.762    0.000    0.762    0.000 <string>:1(<lambda>)
        1    0.000    0.000    7.180    7.180 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 run04.py:1(cycle01)
        1    0.000    0.000    0.000    0.000 run04.py:2(g1)
        1    4.767    4.767    7.180    7.180 run04.py:3(g2)
        1    0.000    0.000    7.180    7.180 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         3333340 function calls in 7.648 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  3333334    0.850    0.000    0.850    0.000 <string>:1(<lambda>)
        1    0.000    0.000    9.370    9.370 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 run04.py:19(cycle02)
        1    0.000    0.000    0.000    0.000 run04.py:20(g1)
        1    6.797    6.797    9.370    9.370 run04.py:21(g2)
        1    0.000    0.000    9.370    9.370 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

  • [ ] # ? 为什么call减少了,时间长了,效率变低了
import cProfile
import re

def count_partitions_1(n, m):
    if n == 0:
        return 1
    elif n < 0:
        return 0
    elif m == 0:
        return 0
    else:
        with_m = count_partitions_1(n-m, m)
        without_m = count_partitions_1(n, m-1)
        return with_m + without_m

def count_partitions_2(n, m):
    if n == 0:
        return 1
    elif n < 0:
        return 0
    elif m == 0:
        return 0
    elif (n-m) <= m:
        with_m = count_partitions_2(n-m, n-m)
        without_m = count_partitions_2(n, m-1)
        return with_m + without_m
    elif (n-m) > m:
        with_m = count_partitions_2(n-m, m)
        without_m = count_partitions_2(n, m-1)
        return with_m + without_m

cProfile.run("count_partitions_1(20,19)")
cProfile.run("count_partitions_2(20,19)")
cProfile.run("count_partitions_1(40,39)")
cProfile.run("count_partitions_2(40,39)")
cProfile.run("count_partitions_1(60,59)")
cProfile.run("count_partitions_2(60,59)")
cProfile.run("count_partitions_1(100,90)")
cProfile.run("count_partitions_2(100,90)")

输出

PS C:\Users\nijian> python E:\沐沐\Cousera\cs61a\run.03.py

>>> cProfile.run("count_partitions_1(20,19)")

         6174 function calls (4 primitive calls) in 0.006 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.005    0.005 <string>:1(<module>)
   6171/1    0.005    0.000    0.005    0.005 run.03.py:4(count_partitions_1)
        1    0.000    0.000    0.006    0.006 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_2(20,19)")

         5428 function calls (4 primitive calls) in 0.006 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.006    0.006 <string>:1(<module>)
   5425/1    0.006    0.000    0.006    0.006 run.03.py:16(count_partitions_2)
        1    0.000    0.000    0.006    0.006 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_1(40,39)")

         455648 function calls (4 primitive calls) in 0.408 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.408    0.408 <string>:1(<module>)
 455645/1    0.408    0.000    0.408    0.408 run.03.py:4(count_partitions_1)
        1    0.000    0.000    0.408    0.408 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_2(40,39)")

         430616 function calls (4 primitive calls) in 0.460 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.460    0.460 <string>:1(<module>)
 430613/1    0.460    0.000    0.460    0.460 run.03.py:16(count_partitions_2)
        1    0.000    0.000    0.460    0.460 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_1(60,59)")

         13748768 function calls (4 primitive calls) in 12.295 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   12.295   12.295 <string>:1(<module>)
13748765/1   12.295    0.000   12.295   12.295 run.03.py:4(count_partitions_1)
        1    0.000    0.000   12.295   12.295 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_2(60,59)")

         13278698 function calls (4 primitive calls) in 14.252 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   14.252   14.252 <string>:1(<module>)
13278695/1   14.252    0.000   14.252   14.252 run.03.py:16(count_partitions_2)
        1    0.000    0.000   14.252   14.252 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_1(100,90)")

         -944290126 function calls (4 primitive calls) in 3059.177 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000 3059.177 3059.177 <string>:1(<module>)
-944290129/1 3059.177   -0.000 3059.177 3059.177 run.03.py:4(count_partitions_1)
        1    0.000    0.000 3059.177 3059.177 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

>>> cProfile.run("count_partitions_2(100,90)")

         -1008982726 function calls (4 primitive calls) in 4684.674 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000 4684.674 4684.674 <string>:1(<module>)
-1008982729/1 4684.674   -0.000 4684.674 4684.674 run.03.py:16(count_partitions_2)
        1    0.000    0.000 4684.674 4684.674 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,289评论 0 10
  • 1.函数:就是对实现某一特定功能的代码块的封装 2.作用:封装(将功能绑定在一个函数中,想要使用这个功能的时候,直...
    随雪而世阅读 248评论 0 3
  • 妈妈,你干嘛把你的头发染成红色,头发本来不就是黑色吗? 是啊!红色不好看吗? 恩....,不好看,我还是觉的黑色好...
    左左_88阅读 292评论 0 0
  • 1、听《婷婷唱古诗》《鹅妈妈》一直在听,自己学起来真难。孩子瞎呜噜音调还很接近。 2、看英文动画片 3、读 阅读《...
    马行千里玥溢彩阅读 155评论 0 0
  • 未经允许,不得擅自改动和转载 原创/阿小庆 写於2019.01.06 说实话,我打心底里感谢这个互联网时代,因为我...
    双愚阅读 2,591评论 0 38