码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-18 16:40:54      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:python   递归   鸡兔同笼   回文   fibonacci   

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)



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

标签:python   递归   鸡兔同笼   回文   fibonacci   

原文地址:http://blog.csdn.net/muzilanlan/article/details/45823827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!