MIT 6.00.1x 第五讲-递归Recursion
** iterative algorithms-- 迭代算法
作业一
Write an iterative function iterPower(base, exp) that calculates the exponential baseexp by simply using successive multiplication. For example, iterPower(base, exp) should compute baseexp by multiplying base times itself exp times. Write such a function below.
This function should take in two values - base can be a float or an integer; exp will be an integer ≥ 0. It should return one numerical value. Your code must be iterative - use of the ** operator is not allowed.
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
while exp > 0:
result *= base
exp -= 1
return(result)
1. Recursive Algorithms
递归函数拥有两个组成部分:
- recursive step:将问题不断简化成更简单的相同问题的步骤;
- base case:问题简化完成后剩下来的可以直接计算的小case
- 每一次的recursive call都会创建一个独立的环境,with local scoping of variables;当其中的一个function有返回值时,此返回值便会一层一层被带入上一层以计算出最终的结果。
2. “Classic” recursive problems
- Factorial 阶乘
def factI(n):
"""interative method
assumes that n is an int > 0
returns n!"""
res = 1
while n > 1:
res = res * n
n -= 1
return res
def factR(n):
"""recursive method
assumes that n is an int > 0
returns n!"""
if n == 1:
return n
return n*factR(n-1)
作业二
Write a function recurPower(base, exp) which computes baseexp by recursively calling itself to solve a smaller version of the same problem, and then multiplying the result by base to solve the initial problem.
This function should take in two values - base can be a float or an integer; exp will be an integer ≥0. It should return one numerical value. Your code must be recursive - use of the ** operator or looping constructs is not allowed.
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp == 0:
result = 1
else:
result = base * recurPower(base, exp-1)
return result
作业三
The function recurPower(base, exp) from Problem 2 computed baseexp by decomposing the problem into one recursive case and one base case:
baseexpbaseexp==base⋅baseexp−11ifexp>0ifexp=0
Another way to solve this problem just using multiplication (and remainder) is to note that
baseexpbaseexpbaseexp===(base2)exp2base⋅baseexp−11ifexp>0andexpisevenifexp>0andexpisoddifexp=0
Write a procedure recurPowerNew which recursively computes exponentials using this idea.
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp <