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

運(yùn)行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:

運(yùn)算符 描述
** 指數(shù) (最高優(yōu)先級(jí))
~ + - 按位翻轉(zhuǎn), 一元加號(hào)和減號(hào) (最后兩個(gè)的方法名為 +@ 和 -@)
* / % // 乘阅悍,除,取模和取整除
+ - 加法減法
>> << 右移,左移運(yùn)算符
& 位 'AND'
^ | 位運(yùn)算符
<= < > >= 比較運(yùn)算符
<> == != 等于運(yùn)算符
= %= /= //= -= += *= **= 賦值運(yùn)算符
is is not 身份運(yùn)算符
in not in 成員運(yùn)算符
not 邏輯運(yùn)算符
and 邏輯運(yùn)算符
or 邏輯運(yùn)算符

/ // %

True Division: / (decimal division)

Floor Division: // (integer division) 整數(shù)部分

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] 是值還是參數(shù)名梳虽?

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內(nèi)挖函,將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


如何判斷函數(shù)的執(zhí)行效率: 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)")
""""""

輸出結(jié)果

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減少了巷怜,時(shí)間長(zhǎng)了呢袱,效率變低了
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}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末姆蘸,一起剝皮案震驚了整個(gè)濱河市墩莫,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌逞敷,老刑警劉巖狂秦,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異推捐,居然都是意外死亡裂问,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門牛柒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來堪簿,“玉大人,你說我怎么就攤上這事皮壁〈魉Γ” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵闪彼,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我协饲,道長(zhǎng)畏腕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任茉稠,我火速辦了婚禮描馅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘而线。我一直安慰自己铭污,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布膀篮。 她就那樣靜靜地躺著嘹狞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪誓竿。 梳的紋絲不亂的頭發(fā)上磅网,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音筷屡,去河邊找鬼涧偷。 笑死簸喂,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的燎潮。 我是一名探鬼主播喻鳄,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼确封!你這毒婦竟也來了除呵?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤隅肥,失蹤者是張志新(化名)和其女友劉穎竿奏,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體腥放,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡泛啸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了秃症。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片候址。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖种柑,靈堂內(nèi)的尸體忽然破棺而出岗仑,到底是詐尸還是另有隱情,我是刑警寧澤聚请,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布荠雕,位于F島的核電站,受9級(jí)特大地震影響驶赏,放射性物質(zhì)發(fā)生泄漏炸卑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一煤傍、第九天 我趴在偏房一處隱蔽的房頂上張望盖文。 院中可真熱鬧,春花似錦蚯姆、人聲如沸五续。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)疙驾。三九已至,卻和暖如春郭毕,著一層夾襖步出監(jiān)牢的瞬間荆萤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留链韭,地道東北人偏竟。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像敞峭,于是被迫代替她去往敵國(guó)和親踊谋。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,325評(píng)論 0 10
  • 1.函數(shù):就是對(duì)實(shí)現(xiàn)某一特定功能的代碼塊的封裝 2.作用:封裝(將功能綁定在一個(gè)函數(shù)中旋讹,想要使用這個(gè)功能的時(shí)候殖蚕,直...
    隨雪而世閱讀 253評(píng)論 0 3
  • 媽媽,你干嘛把你的頭發(fā)染成紅色沉迹,頭發(fā)本來不就是黑色嗎睦疫? 是啊鞭呕!紅色不好看嗎蛤育? 恩....,不好看葫松,我還是覺的黑色好...
    左左_88閱讀 296評(píng)論 0 0
  • 1瓦糕、聽《婷婷唱古詩(shī)》《鵝媽媽》一直在聽,自己學(xué)起來真難腋么。孩子瞎嗚嚕音調(diào)還很接近咕娄。 2、看英文動(dòng)畫片 3珊擂、讀 閱讀《...
    馬行千里玥溢彩閱讀 157評(píng)論 0 0
  • 未經(jīng)允許圣勒,不得擅自改動(dòng)和轉(zhuǎn)載 原創(chuàng)/阿小慶 寫於2019.01.06 說實(shí)話,我打心底里感謝這個(gè)互聯(lián)網(wǎng)時(shí)代摧扇,因?yàn)槲?..
    雙愚閱讀 2,596評(píng)論 0 38