MITx - 6.00.1x 笔记(2) Simple Programs

Simple Programs

二分法能够极大地减少运算时间
Bisection Search
Bisection Search2

穷举法

计算机如何处理浮点数
float numbers

Newton-Raphson方法

牛顿迭代法(Newton’s method)又称为牛顿-拉夫逊方法(Newton-Raphson method)
Newton_Raphson

使用牛顿迭代法来计算平方根
apply_newton_method_1

apply_newton_method_2

→迭代算法

Iterative_Algorithm


什么是好的程序

  • 不以代码量为依据
  • 注重代码的功能
  • 使用函数
  • 能进行分离(模块化)和抽象

GoodProgramming

模块化(function, class)、抽象出方法
apply


递归 recursion

recursion
简化函数,可在函数内部调用自身,注意需要设定基准情况防止无限循环。

递归应用举例:
apply_recursion

迭代 vs. 递归

Iteration vs. Recursion
从程序员角度来说,使用递归方法更省心更高效,不用另外定义变量。

数学归纳
mathematical_induction

彩蛋:Tower of Hanoi solution with recursion
tower of hanoi

def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
    # n为需要移动的套圈的个数
    # fr, to, spare 为位置
    if n == 1:
        printMove(fr, to)
    else:
        Towers(n-1, fr, spare, to)
        Towers(1, fr, to, spare)
        Towers(n-1, spare, to, fr)

测试:

print(Towers(4, "P1", "P2", "P3"))

结果:

move from P1 to P3
move from P1 to P2
move from P3 to P2
move from P1 to P3
move from P2 to P1
move from P2 to P3
move from P1 to P3
move from P1 to P2
move from P3 to P2
move from P3 to P1
move from P2 to P1
move from P3 to P2
move from P1 to P3
move from P1 to P2
move from P3 to P2
None

通过iteration很难完成的任务,用recursion方法可以轻松完成。

→ 总思路:分解为简化版方法

练习1:用iteration计算最大公约数(Greatest Common Divisor,缩写为gcd)。

def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Your code here
    gcd = min(a, b)
    while (a % gcd != 0) or (b % gcd != 0):
        #print("a% gcd: ", a % gcd)
        #print("b% gcd: ", b % gcd)
        #print("tmp: ", gcd)
        gcd -= 1

    return gcd

练习2:用Iteration借助欧几里德算法(Euclid’s algorithm )计算最大公约数

  • 定理:两个整数的最大公约数等于其中较小的那个数和两数相除余数的最大公约数。即:gcd(a,b) = gcd(b,a mod b)。 (不妨设a>b 且r=a mod b ,r不为0)
def gcdRecur(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Your code here
    if b == 0:
        return a
    else:
        return gcdRecur(b, a % b)

斐波那契数与递归方法
Fibonacci number
Fibonacci

def fib(x):
    """assumes x an integer >= 0
    return Fibonacci of x"""
    if x ==0 or x == 1:
        return 1
    else:
        return fib(x-1) + fib(x-2)

用递归检测回文(palindrome)
Recursion on non_numberics

  • 首先去除标点,转换为小写字母
  • 递归方法:
    • 基准情况:如果长度为0或1,符合
    • 递归情况:
      • 如果第一个字母和最后的子母相同, 依次对称检查内部对应位置的字母是否相同

apply ispalindrome

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值