[英]How to use faulhaber sequence in python?
I am trying to code a function. 我正在尝试编写一个函数。 The function accepts two parameters, k and n.
该函数接受两个参数k和n。 It should return the sum of the k-th powers of the numbers from 1 to n.
它应该返回从1到n的数字的第k个幂的总和。 For example, sumPowerN(1, 3) should return 6 The answer for the above example is 6 because 1^1 + 2^1 + 3^1 = 6
例如,sumPowerN(1,3)应该返回6以上示例的答案是6,因为1 ^ 1 + 2 ^ 1 + 3 ^ 1 = 6
This is what I've done so far; 这就是我到目前为止所做的事情;
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()
Please help. 请帮忙。 I am really stuck.
我真的被卡住了。 And please do point out what I'm doing wrong because I am still new to Python.
请指出我做错了什么,因为我还是Python新手。
def sumPowerN(k,n):
result = 0
for n in range(1, n+1):
result = result + (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()
resulted in: 导致:
$ 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, '.')
You don't need to keep adding the 1 and 2 powers; 你不需要继续增加1和2的权力; just use the fact that range will give you the entire list of bases to be raised.
只需使用范围将为您提供整个基数列表的事实。
def sum_power_n(k, n):
result = 0
for i in range(1, n+1):
result += i**k
return result
Fucntional approach: 功能方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.