起因
我们有三个函数:
- 第一个函数计算前n个自然数的和
- 第二个函数计算前n个自然数的立方和
- 第三个函数计算一个序列
这三个函数定义如下
# -*- coding : utf-8 -*-
def sum_naturals(n):
""" Return sum of the first n natural numbers
"""
total, k = 0, 0
while(k <= n):
total, k = total + k, k + 1
return total
def sum_cubes(n):
""" Compute the sum of the cubes of natural number up to n
"""
total, k = 0, 0
while(k <= n):
total, k = total + k * k * k, k + 1
return total
def pi_sum(n):
total, k = 0, 1
while k <= n:
total, k = total + 8 / ((4*k-3) * (4*k-1)), k + 1
return total
我们发现这三个函数有着相同的模式,除了具体每次新加的表达式不同,其余的模式是相同的
def <name>(n):
total, k = 0, 1
while k <= n:
total, k = total + <term>(k), k + 1
return total
解决
那么作为python的程序员,我们就想让程序更加的简单,那么我们可以采取下面的做法,将具体的函数作为另一个模版函数的参数
summation()是模版函数
# -*- coding : utf-8 -*-
## Model
def summation(n, term):
total, k = 0, 0
while(k <= n):
total, k = total + term(k), k + 1
return total
def identity(x):
return x
def cube_operator(x):
return x * x * x
def pi_operator(x):
return 8 / ((4*x-3) * (4*x-1))
# final functions
def sum_naturals(n):
return summation(n, identity)
def sum_cubes(n):
return summation(n, cube_operator)
def sum_pi(n):
return summation(n, pi_operator)
网友评论