MIT公开课:计算机科学及编程导论 Python 笔记4 函数分解抽象与递归

Lecture4:Decomposition and abstraction through functions;introduction to recursion 函数分解抽象与递归

Functions 函数

  • block up into modules 分解为模块
  • suppress detail 忽略细节
  • create “new primitives” 创建原语的思考方式

    w3school Python函数

#example code for finding square roots before
x = 16
ans = 0
if x >= 0:
    while ans*ans < x:
        ans = ans + 1
        print ‘ans =‘, ans
    if ans*ans != x:
        print x, ‘is not a perfect square‘
    else: print ans
else:  print x, ‘is a negative number‘
  • def 关键字
  • function_name (formal parameters) 函数名(形参)
  • return 关键字
  • None -special value
#example code for finding square roots

def sqrt(x):
  """Returns the square root of x, if x is a perfect square.
       Prints an error message and returns None otherwise"""
  ans = 0
  if x >= 0:
      while ans*ans < x: ans = ans + 1
      if ans*ans != x:
          print x, ‘is not a perfect square‘
          return None
      else: return ans
  else:
        print x, ‘is a negative number‘
        return None

local binding do not affect global binding:

本地绑定(局部变量)不会影响 全局绑定(变量):

def f(x): x=x+1
return x

>>>x=3
>>>z = f(x)
>>>print x
3
>>>print z
4


Farmyard problem 农场问题:

  • 20 heads, 56 legs
  • numPig + numChicken = 20 猪的数量+鸡的数量 = 20
  • 4 *numPig + 2*numChicken = 56
def solve(numLegs, numHeads):
    for numChicks in range(0, numHeads + 1):
        numPigs = numHeads - numChicks
        totLegs = 4*numPigs + 2*numChicks
        if totLegs == numLegs:
            return (numPigs, numChicks)
    return (None, None)

def barnYard():
    heads = int(raw_input(‘Enter number of heads: ‘))
    legs = int(raw_input(‘Enter number of legs: ‘))
    pigs, chickens = solve(legs, heads)
    if pigs == None:
        print ‘There is no solution‘
    else:
        print ‘Number of pigs:‘, pigs
        print ‘Number of chickens:‘, chickens

农场主又养了蜘蛛:

def solve1(numLegs, numHeads):
    for numSpiders in range(0, numHeads + 1):
        for numChicks in range(0, numHeads - numSpiders + 1):
            numPigs = numHeads - numChicks - numSpiders
            totLegs = 4*numPigs + 2*numChicks + 8*numSpiders
            if totLegs == numLegs:
                return (numPigs, numChicks, numSpiders)
    return (None, None, None)

def barnYard1():
    heads = int(raw_input(‘Enter number of heads: ‘))
    legs = int(raw_input(‘Enter number of legs: ‘))
    pigs, chickens, spiders = solve1(legs, heads)
    if pigs == None:
        print ‘There is no solution‘
    else:
        print ‘Number of pigs:‘, pigs
        print ‘Number of chickens:‘, chickens
        print ‘Number of spiders:‘, spiders

改进:输出所有的解决方案:

def solve2(numLegs, numHeads):
    solutionFound = False
    for numSpiders in range(0, numHeads + 1):
        for numChicks in range(0, numHeads - numSpiders + 1):
            numPigs = numHeads - numChicks - numSpiders
            totLegs = 4*numPigs + 2*numChicks + 8*numSpiders
            if totLegs == numLegs:
                print ‘Number of pigs: ‘ + str(numPigs) + ‘,‘,
                print ‘Number of chickens: ‘+str(numChicks)+‘,‘,
                print ‘Number of spiders:‘, numSpiders
                solutionFound = True
    if not solutionFound: print ‘There is no solution.‘


recursion 递归

  • base case – break problem into simplest possible solution把问题分解成最简单的解决方案
  • inductive step, or the recursive step 归纳、递归步骤: break problem into a simpler version of the same problem and some other steps
# 字符串是否是回文 eg. "abcba"
def isPalindrome(s):
    """Returns True if s is a palindrome and False otherwise"""
    if len(s) <= 1: return True
    else: return s[0] == s[-1] and isPalindrome(s[1:-1])
# 付波纳切fibonacci数列
def fib(x):
    """Return fibonacci of x, where x is a non-negative int"""
    if x == 0 or x == 1: return 1
    else: return fib(x-1) + fib(x-2)



时间: 2024-12-13 03:05:25

MIT公开课:计算机科学及编程导论 Python 笔记4 函数分解抽象与递归的相关文章

MIT麻省理工学院公开课:计算机科学及编程导论 Python 笔记1-3

Lecture1:Goals of the course; what is computation; introduction to data types, operators, and variables Python High (√) VS. low General (√) VS. targetted Interpreted (√) VS. compile Syntax语法:what are legal expressions "cat dog boy " Static seman

MIT公开课:计算机科学及编程导论 Python 笔记5 浮点数,逐次逼近法和二分法

Lecture5: Floating point number , successive refinement, finding roots 浮点数和二分法 3wschool 数字 >>> a = 2 ** 1000 >>> a 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251

计算机科学及编程导论学习笔记

不要频繁变换变量的类型 多用有意义的通俗易懂的变量名 python的raw_input的值都默认为字符串 “=”是用来赋值的,将左边的名字绑定到右边的值上去.因此比较的时候要用“==” if <测试语句> :

计算机科学及编程导论(4)函数抽象与递归

position:static(静态定位) 当position属性定义为static时,可以将元素定义为静态位置,所谓静态位置就是各个元素在HTML文档流中应有的位置 podisition定位问题.所以当没有定义position属性时,并不说明该元素没有自己的位置,它会遵循默认显示为静态位置,在静态定位状态下无法通过坐标值(top,left,right,bottom)来改变它的位置. position:absolute(绝对定位) 当position属性定义为absolute时,元素会脱离文档流

计算机科学及编程导论(7)数组及可变性、字典、伪代码,代码运行效率简介

1. 数组及可变性 当创建一个数组的时候,它将与一个对象进行绑定 L1 = [1, 2, 3] L2 = L1 L1[0] = 4 print(L2)#=>[4, 2, 3] L2 = L1 意味着L2与L1指向同一个对象,而L1[0]=4则改变了对象的值,所以最终L2的值也会改变,可以与下面这个例子进行比较 a = 1 #a指向对象1 b = a #b指向对象a a = 4 #此时a指向了对象4 print(b) #=>1,由于b依旧指向对象1,所以没有发生变化 2.字典 字典包括了以下几个

计算机科学及编程导论(3)迭代程序的设计与实现、遍历、元组

1. 迭代程序的设计:基础元素 迭代程序的实现,通常包括下了以下五个部分: 计数器(Count):用于标记循环的次数 初始化(Initiate):在循环外部进行初始化 正确的结束测试(Right End Test):在什么情况下结束通常与计数器(Count)密切相关 循环部分的代码块:该部分代码块通常包含了对计数器的改变 结束后程序应该做什么 2. 迭代程序的设计:流程图 在使用具体的代码实现之前,可以用流程图来组织程序. 举一个简单的例子,已经一个正整数的平方为X,要求这个正整数,可以设这个正

计算机科学及编程导论(5)浮点数和二分法

1. Python的数字类型 Python的数字类型分为两类:整型(int)以及浮点型(float). 对于Python来说,整型可以取无限大. Python的整型可以取任意精度 例如,可以输入2**1000次方,仍然会返回正确结果. Python的浮点类型按照IEE754标准,对于64位的计算机而言,表示成如下方式 1位:符号位 11位:指数位 52位:尾数位 这样总共可以表示17位长的精度,如果超过17位,Python就无法处理,比如 0.1**1000次方. 在教学视频中,如果输入 x =

计算机科学及编程导论(8)算法的复杂度

1.基于问题规模的复杂度计算方法 在考虑时间效率的时候,面临以下两个问题:输入规模以及步骤. 输入规模受很多因素影响:参数大小.参数类型(数组.元组的存取小绿是不同的),而且不同操作步骤(加减.判断)时间也不是相同的,为了方便计算,我们需要建立以下的假设: 假设从计算机取得任何变量的时间是相同的 假设基本操作时间恒定 接下来就可以考虑以下几种情况: 最好情况:何种输入会使得程序的运行时间最短? 最坏情况:何种输入会使得程序的运行时间最长? 平均情况 如果考虑平均情况的话,就要去设想问题输入规模的

斯坦福大学公开课:iOS 7应用开发 笔记

2015-07-06 第一讲   课务.iOS概述 -------------------------------------------------- 开始学习斯坦福大学公开课:iOS 7应用开发留下笔记