这是一个计算从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()
谢谢你的帮助。我知道我不能迭代函数,但我完全被难住了
iter
或yield
代码:
结果:
你的职能:
返回按立方计算的数字列表。在这种情况下,函数
def sum_of_cubics(n):
可以是:另外,请注意
sum
是一个内置函数。因此,请避免使用内置函数作为变量您应该更改
for
循环以使用值n
调用cubics
函数。这将返回您的cubelist
,因此您正在遍历它。在连续迭代中,i
将被设置为1、8、27等然后,您只需将
i
添加到您的跑步总量中(就像burningalc所说的,称之为与sum
不同的东西)。所以你的第二个功能变成:相关问题 更多 >
编程相关推荐