如何在python中使用faulhaber序列?

2024-10-01 22:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数。函数接受两个参数k和n。它应该返回从1到n的数字的k次幂和。 例如,sumpowrn(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 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新手。在


Tags: oftheto函数answervaluemaindef
3条回答

你不需要一直加上1和2的幂,只要使用范围会给你所有要提升的基的列表。在

def sum_power_n(k, n):
    result = 0
    for i in range(1, n+1):
       result += i**k
    return result
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()

结果:

^{pr2}$

功能方法:

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

相关问题 更多 >

    热门问题