您将如何为summer(n,f)编写测试代码,这有什么问题吗?

2024-04-20 04:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

def noah(x):
    return x*x*x
def summer(n, f):
    """precondition: n is a nonnegative number and f is a function
    whose domain includes the nonnegative integres
    postcondition:  returns sum( f(k),  k = 1..n) """
    y = 0
    for i in range (1, n + 1):
        y = y + f(i)
    return y

Tags: andthenumberreturnisdomaindeffunction
3条回答
# You should verify preconditions in the summer function's body
def summer(n, f):
    if n < 0: 
        raise ValueError(str(n) + ' < 0') # check that n > 0
    if not isinstance(f, types.FunctionType): 
        raise ValueError('f is not a function') # check f is a function
    y = 0
    for i in range (1, n + 1):
        y = y + f(i)
    return y


### Test part ###
import unittest

class TestSummer(unittest.TestCase):

def test_precond1(self):
    """Check that if n < 0, raise ValueError"""
    self.assertRaises(ValueError, summer, -1, noah)

def test_precond2(self):
    """Check that if f is not a function, raise ValueError"""
    self.assertRaises(ValueError, summer, 1, 'str')

def test_result(self):
    """Check that summer(3, noah) is equal to 32"""
    self.assertTrue(summer(3, noah), 32)  # f(1) + f(2) + f(3) = 1 + 8 + 27 = 32

unittest.main()

递归是你的朋友。你知道吗

def summer(n, f):
    if n == 0:
        return 0
    return f(n) + summer(n-1, f)

另一种方法是用f映射范围列表:

sum(map(lambda x: f(x), range(1, n+1)))        

嗯。。。使用发电机似乎更容易:

 sum(f(x) for x in range(1,n+1))       (Python 3)
 sum(f(x) for x in xrange(1,n+1))      (Python 2)

相关问题 更多 >