在新函数中迭代以前生成的函数的值

2024-10-02 00:43:21 发布

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

这是一个计算从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()

谢谢你的帮助。我知道我不能迭代函数,但我完全被难住了


Tags: oftheto函数fromyourheredef
3条回答
  • 如果必须遍历函数,可以尝试使用iteryield

代码:

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 iter(cubelist)
    else:
        raise ValueError('Error')

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(n):
        sum += i
    return sum

print(sum_of_cubics(5))

结果:

225

你的职能:

def cubics(n):

返回按立方计算的数字列表。在这种情况下,函数def sum_of_cubics(n):可以是:

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

另外,请注意sum是一个内置函数。因此,请避免使用内置函数作为变量

您应该更改for循环以使用值n调用cubics函数。这将返回您的cubelist,因此您正在遍历它。在连续迭代中,i将被设置为1、8、27等

然后,您只需将i添加到您的跑步总量中(就像burningalc所说的,称之为与sum不同的东西)。所以你的第二个功能变成:

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

相关问题 更多 >

    热门问题