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()
感谢您的任何帮助。我知道我不能遍历一个函数,但我完全被难住了。
解决方案
你的功能:
def cubics(n):
返回数字的立方列表。在这种情况下,您的功能def sum_of_cubics(n):
可以是:
def sum_of_cubics(n):
return sum(cubics(n))
另外,请注意这sum
是一个内置功能。所以请不要使用内置函数作为变量
推荐阅读
- python - 康威生命游戏仅在两帧之间切换 - Python
- firebase - 错误:获取存储源时出错:generic::unknown... 通过 GitHub Actions 部署 GCP Cloud Function 时
- python - Python - 拆分列表中包含的数据帧
- c# - 如何模拟包装的 Microsoft ASP.NET Core 客户端 SignalR HubConnection 类?
- sql - 在plsql中的以下数据中查找重叠
- python - 如何在 Python 中修复这个特定的“TypeError:'str' object is not callable”错误?(初学者问题)
- sql - 我们如何在 ORACLE 正则表达式中对(字符类)进行例外处理?
- r - R中生存分析协变量的MLE模拟数据
- python - 在 Python 中迭代列表并找到合适的字符串模式的最快(最有效)方法是什么?
- javascript - Javascript 错误 appendChild 不是函数