如何在python中使用函数添加多维数据集的总和



我可以得到多维数据集的答案,但我真的不知道从这里到哪里才能得到返回答案并不断将其添加到和中的函数!我该怎么做才能让它不断相加得到一个总数?

def sumNCubes(n):
    for i in range(n)
    return (n-1)**3
def main():
    number = int(raw_input("What number do you want to find the sum of cubes for?"))
    n = number + 1
    for i in range(number):
        n = n - 1 
    print "The result of the sums is:", sumNCubes(n)
main()

您可以简单地执行以下操作:

def sumNCubes(n):
    return sum(i**3 for i in range(1,n+1))

其使用对从1-n+1(1-n将不包括n)的范围内的立方体数的列表理解,然后使用CCD_。

然后你可以直接输入并打印:

def main():
    number = int(raw_input("What number do you want to find the sum of cubes for?"))
    #this doesn't do anything but change n to 0
    #for i in range(number):
    #    n = n - 1 
    print "The result of the sums is:", sumNCubes(number)
main()

例如,输入5后,将返回:

>>> sumNCubes(5)
225

答案很简单。这将通过递归方法给出。

这是一个函数,可以找到N个数字的总和,你非常接近这个

def sumNcubes(n):
  if (n == 1):
    return 1
  else:
    return n**3 + sumNcubes(n-1)
>>>sumNcubes(6)
441

不使用n**3

def sum_cubes (n):
    b, c, sum = 1, 0, 0
    for a in range(0, 6*n, 6):
        sum += (c := c + (b := b + a))
    return sum

无环路

 def sum_cubes (n):
     return (n*(n+1)//2)**2

最新更新