天天看点

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