标签:python 递归 鸡兔同笼 回文 fibonacci
Functions 函数
#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‘
#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 农场问题:
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 递归
# 字符串是否是回文 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