首页 > 解决方案 > 在新函数中迭代先前创建的函数的值的问题

问题描述

这是一个计算从 1 到 n 的三次方的函数。

def cubics(n):
    """Compute the cubics of numbers from 1 to n, such that the 
    ith element of the returned list equals i^3.
    
    """
    # YOUR CODE HERE
    if n >= 1:
        cubelist = [i**3 for i in range (1, n +1)]
        return cubelist
    else:
        raise ValueError('Error')
    raise NotImplementedError()

我需要创建一个新函数,它使用我的三次函数来计算从 1 到 n 的数字的三次之和。这是我迄今为止尝试过的并且遇到了问题。

def sum_of_cubics(n):
    """Compute the sum of the cubics of numbers from 1 to n."""
    # YOUR CODE HERE
    sum = 0
    for i in cubics:
        sum += cubics([i])
    return sum
    raise NotImplementedError()

感谢您的任何帮助。我知道我不能遍历一个函数,但我完全被难住了。

标签: pythonfunction

解决方案


你的功能:

def cubics(n):

返回数字的立方列表。在这种情况下,您的功能def sum_of_cubics(n):可以是:

def sum_of_cubics(n):
    return sum(cubics(n))

另外,请注意这sum是一个内置功能。所以请不要使用内置函数作为变量


推荐阅读