2017-04-10 42 views
1

我想編寫一個函數。該函數接受兩個參數k和n。它應該返回從1到n的數字的第k個冪的和。 例如,sumPowerN(1,3)應返回6 以上示例的答案是6,因爲1^1 + 2^1 + 3^1 = 6如何在python中使用faulhaber序列?

這是我迄今爲止所做的;

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還是一個新手。

+0

您正在使用什麼版本的Python? –

回答

1
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() 

導致:

$ 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, '.') 
-1

Fucntional方法:

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 
+0

爲什麼downvoting?從我的觀點來看,這個問題可能不是一個有用的答案,但是在問題的背景下,一個非常有趣的方法值得在那裏出現,不是嗎? – Claudio

0

你並不需要不斷增加的1分2的權力;只是使用範圍會給你所有基地的整個清單的事實。

def sum_power_n(k, n): 
    result = 0 
    for i in range(1, n+1): 
     result += i**k 
    return result 
+0

我做了你所說的。它仍然出錯 – babyblue

相關問題