如何在python中使用faulhaber序列?
我正在尝试编写一个函数。该函数接受两个参数k和n。它应该返回从1到n的数字的k次幂的和。 例如,sumPowerN(1,3)应该返回6 上面例子的答案是6,因为1^1+2^1+3^1=6 这就是我到目前为止所做的如何在python中使用faulhaber序列?,python,Python,我正在尝试编写一个函数。该函数接受两个参数k和n。它应该返回从1到n的数字的k次幂的和。 例如,sumPowerN(1,3)应该返回6 上面例子的答案是6,因为1^1+2^1+3^1=6 这就是我到目前为止所做的 def sumPowerN(k,n): result = 0 for n in range(1, n+1, n): result = result + (1 ** k) + (2 ** k) + (n ** k) return resul
def sumPowerN(k,n):
result = 0
for n in range(1, n+1, n):
result = result + (1 ** k) + (2 ** k) + (n ** k)
return result
def main():
print("Program to calculate sum of k-th powers of numbers from 1 to n")
kVal, nVal = input("Please enter the k-th value and the n-th value (k,n): ")
answer = sumPowerN(kVal, nVal)
print("The value of the sum is:", answer ,".")
main()
请帮忙。我真的被卡住了。请指出我做错了什么,因为我还是Python新手。功能方法:
import operator
import itertools
def sumPowerN(k,n):
return sum(itertools.imap(lambda x:operator.pow(x, k), xrange(1, n+1)))
sumPowerN(1,3)
6
功能性方法:
import operator
import itertools
def sumPowerN(k,n):
return sum(itertools.imap(lambda x:operator.pow(x, k), xrange(1, n+1)))
sumPowerN(1,3)
6
你不需要一直加1和2的幂;只要利用这个事实,range将为您提供要提升的所有基础列表
def sum_power_n(k, n):
result = 0
for i in range(1, n+1):
result += i**k
return result
你不需要一直加1和2的幂;只要利用这个事实,range将为您提供要提升的所有基础列表
def sum_power_n(k, n):
result = 0
for i in range(1, n+1):
result += i**k
return result
导致:
$ python sumPowerN_Cg.py
Program to calculate sum of k-th powers of numbers from 1 to n
Please enter the k-th value and the n-th value (k,n): 1,3
('The value of the sum is:', 6, '.')
导致:
$ python sumPowerN_Cg.py
Program to calculate sum of k-th powers of numbers from 1 to n
Please enter the k-th value and the n-th value (k,n): 1,3
('The value of the sum is:', 6, '.')
为什么要投否决票?在我看来,这也许不是一个有用的答案,但在这个问题的背景下,一个非常有趣的方法值得一提,不是吗?为什么要投否决票?在我看来,这也许不是一个有用的答案,但在这个问题的上下文中,一个非常有趣的方法值得一提,不是吗?您使用的是什么版本的Python?您使用的是什么版本的Python?