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)