-1
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
4

3 回答 3

0
# 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()
于 2013-10-10T22:02:25.190 回答
0

递归是你的朋友。

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)))        
于 2013-10-10T21:50:21.783 回答
0

好吧......使用生成器似乎更容易:

 sum(f(x) for x in range(1,n+1))       (Python 3)
 sum(f(x) for x in xrange(1,n+1))      (Python 2)
于 2013-10-10T22:04:49.747 回答