美文网首页
2018-07-24

2018-07-24

作者: mumupluto | 来源:发表于2018-07-24 10:44 被阅读0次

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}

相关文章

网友评论

      本文标题:2018-07-24

      本文链接:https://www.haomeiwen.com/subject/lgremftx.html