天天看點

Think Python: Chapter 7 Iteration(疊代) 筆記Python Tutorial[4]:Quadratic Roots

目錄

這是麻省理工大學(MIT)官方程式設計教程中Python Tutorial的内容,教材為《Think Python: How to Think Like a Computer Scientist》。這是我的學習筆記,因為水品有限,請大家多多包涵。如果有一起學習的同學可以一起交流。如筆記中錯誤,請一定要告訴我啊,我肯定及時改正。所有筆記的目錄詳見:MIT:Python Tutorial目錄

這是MIT官方程式設計教程中Python Tutorial中Using if, else, and while的内容。本篇部落格為《 Think Python: How to Think Like a Computer Scientist》的第7章 Fruitful Iteration的筆記内容。(Think Python:Chapter 7 Iteration(疊代))和本階段Python Tutorial:Functions and Scope 課後作業題目(QUESTIONS)的部分程式設計。和本階段Python Tutorial:Using if, else, and while 課後作業題目(QUESTIONS)的部分程式設計。

Chapter 7 Iteration(疊代)

7.1 Multiple assignment(多重任務,多次指派)

multiple assignment: Making more than one assignment to the same variable during the execution of a program.(注意指派次序)

7.2 Updating variables

update: An assignment where the new value of the variable depends on the old.

initialization(初始化): An assignment that gives an initial value to a variable that will be updated.

increment(遞增): An update that increases the value of a variable (often by one).

decrement(遞減): An update that decreases the value of a variable.

7.3 The while statement

iteration(疊代): Repeated execution of a set of statements using either a recursive function call or a loop.

Because iteration is so common, Python provides several language features to make it easier. One is the for statement we saw in Section 4.2. We’ll get back to that later.

#5.8 recursion 循環語句-用if
def countdown(n):
    if n<=:
        print('Blastoff')
    else:
        print(n)
        countdown(n-)
           

Another is the while statement. Here is a version of countdown that uses a while statement:

#7.3 iteration 循環語句-用while
def countdown2(n):
    while n>:
        print n
        n=n-
    print('Blastoff')
           

infinite loop(無限循環): A loop in which the terminating condition is never satisfied.

if,while;循環,疊代的差别

if代表的是recursion(循環),是函數裡面再嵌入函數;

while代表的是iteration(疊代),是自動疊代

7.4 break

Sometimes you don’t know it’s time to end a loop until you get half way through the body.In that case you can use the break statement to jump out of the loop:

while True:
    line = raw_input('>' )
    if line == 'done' :
       break
    print line
print ('Done!')
           

7.5 Square roots(二次根)

Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.

For example, one way of computing square roots is Newton’s method. Suppose that you want to know the square root of a . If you start with almost any estimate, x(近似預測) , you can compute a better estimate with the following formula:

y=(x+a/x)/2

疊代程式為:

#7.6 square_roots
def square_roots(x,a):
    epsilon=#精度設定,為了防止無限循環
    while True:
        print(x)
        y=(x+a/x)/
        if abs(y-x)<epsilon:#判斷誤差
            break
        x=y
           

運作效果:

>>> square_roots(,)





           

7.6 Algorithms

Newton’s method is an example of an algorithm: it is a mechanical process for solving a category of problems (in this case, computing square roots).

It is not easy to define an algorithm. It might help to start with something that is not an algorithm. When you learned to multiply single-digit numbers, you probably memorized the multiplication table. In effect, you memorized 100 specific solutions. That kind of knowledge is not algorithmic.

But if you were “lazy,” you probably cheated by learning a few tricks. For example, to find the product of n and 9, you can write n − 1 as the first digit and 10 − n as the second digit. This trick is a general solution for multiplying any single-digit number by 9. That’s an algorithm!

Similarly, the techniques you learned for addition with carrying, subtraction with borrowing, and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out. They are mechanical processes in which each step follows from the last according to a simple set of rules.

In my opinion, it is embarrassing that humans spend so much time in school learning to execute algorithms that, quite literally, require no intelligence.

On the other hand, the process of designing algorithms is interesting, intellectually challenging, and a central part of what we call programming.(算法設計的過程是有趣的,挑戰智力的,但算法設計也是程式設計的核心部分之一)

Some of the things that people do naturally, without difficulty or conscious thought, are the hardest to express algorithmically. Understanding natural language is a good example.We all do it, but so far no one has been able to explain how we do it, at least not in the form of an algorithm.(人有時候會自然地,無意識的思考,但是這些思考很難用算法的方式表達出來。了解自然語言是一個很好的例子,我們都在做,但是目前為止,還沒有人能夠解釋我們是怎麼去做到他的,至少還沒有人能夠用算法的方式表達出來)

7.7 Debugging

As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more place for bugs to hide(代碼越多,bug出現的可能越多).

One way to cut your debugging time is “debugging by bisection(對半分).”(一種減少調試修正bug的方法是将它對半分,并用print()來觀察每個階段的代碼是否正确)

- For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps.Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a print statement (or something else that has a verifiable effect) and run the program.

- If the mid-point check is incorrect, there must be a problem in the first half of the program.If it is correct, the problem is in the second half.

Every time you perform a check like this, you halve the number of lines you have to search.After six steps (which is fewer than 100), you would be down to one or two lines of code,at least in theory.(不斷疊代的半分尋找錯誤)

In practice it is not always clear what the “middle of the program” is and not always possible to check it. It doesn’t make sense to count lines and find the exact midpoint. Instead,think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check.(有時候不可能完全的對半分,那就應該去找最容易可能出錯的或者是最容易檢查的地方插入測試print()..[我個人覺得,在python中,可能使用return()會比較好一點,因為這樣,下面的代碼就不需要運作下去了,也不容易犯錯。我覺得作者的意思應該是用return,而不是print。因為本書是由Java改編過來的,可能給編寫習慣上有所不同])

Question

Problem Wk.3.1.3: Arithmetic if

#Problem Wk.3.1.3: Arithmetic if 
def arithmetic_If(v,a,b,c):
    v=float(v)#初始化讓其為num
    if v>:
        return a
    if v==:
        return b
    if v<:
        return c
           

Problem Wk.3.1.4: Clipping shears

#Problem Wk.3.1.4: Clipping shears 
def clip(lo,x,hi):
    lo=float(lo)
    x=float(x)
    hi=float(hi)
    if x<lo:
        return lo
    if x>hi:
        return hi
    else:
        retur x
           

Problem Wk.3.1.5: Clip clop

不能使用if,使用max和min

#Problem Wk.3.1.5: Clip clop
def clip2(lo,x,hi):
    lo=float(lo)
    x=float(x)
    hi=float(hi)
    if max(x,lo)==lo and x!=lo:
        return lo
    if min(x,hi)==hi and x!=hi:
        return hi
    else:
        return x
           

Problem Wk.3.2.1: Multiple times

#Problem Wk.3.2.1: Multiple times 

def multIA(m,n):
    multi=
    while n>:
        multi=multi+m
        n=n-
    return multi
           

Problem Wk.3.2.2: Multiple times, again

#Problem Wk.3.2.2: Multiple times, again 

def multIAgen(m,n):
    m=int(m)
    n=int(n)
    m1=abs(m)
    n1=abs(n)
    if m< and n<:
        return multIA(m1,n1)
    if m< or n<:
        return (-multIA(m1,n1))
    else:
        return multIA(m1,n1)
           

Problem Wk.3.2.3: A la mod

#Problem Wk.3.2.3: A la mod 

def mod(m,n):
    while m>n:
        m=m-n
    return m
           

Problem Wk.3.2.4: Muad-Div

#Problem Wk.3.2.4: Muad-Div 

def div(m,n):
    divT=
    while m>n:
        divT=divT+
        m=m-n
    return divT
           

Problem Wk.3.2.5: Primo

#Problem Wk.3.2.5: Primo
#這個問題應該是為了确定n是不是單數
def prime(n):
    m=
    while m<=n/:
        if n%m==:
            print(m)#輸出最小因子
            break
        m=m+
    return (m-n/>)
           

Problem Wk.3.2.6: Powers of 2

[沒看懂是什麼意思]

Problem Wk.3.2.7: Perfectly square

#Problem Wk.3.2.7: Perfectly square
def perfectSquare(n):
    import math
    a=math.sqrt(n)
    return int(a)==a
           

Python Tutorial[4]:Quadratic Roots

Problem Wk.4.1.1: Get real

#Problem Wk.4.1.1: Get real
#求二次方程的解
def quadraticRoots(a,b,c):
    if a==:
        x=-c/b
        print(x)

    z=b**-*a*c
    if z==:
        x= -b/(*a)     
        print (x)
    if z<:
        print ('沒有實數根')
    else:
        import math
        x1=(-b+math.sqrt(z))/(*a)
        x2=(-b-math.sqrt(z))/(*a)
        print(x1)
        print(x2)
           

Problem Wk.4.1.2: More complex