1. 程式人生 > >codewars-7kyu:Sum of the first nth term of Series

codewars-7kyu:Sum of the first nth term of Series

Task:

Your task is to write a function which returns the sum of following series upto nth term(parameter).

Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

Rules:

  • You need to round the answer to 2 decimal places and return it as String.

  • If the given value is 0 then it should return 0.00

  • You will only be given Natural Numbers as arguments.

Examples:

SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"

my answer:
def series_sum(n):
    # Happy Coding ^_^
    temp_sum=1
    if n==0:
        temp_sum=0
    while n>1:
        temp_sum+=1/(3*n-2)
        n-=1
    return '
%.2f'%temp_sum

 

優秀程式碼:

def series_sum(n):
    return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))

 

這個網站還是很不錯的,從級數開始練習,每個階段安裝能力來匹配,我覺得這個模式比LeetCode好很多,因為LeetCode一上手感覺還是很難的,我這種菜雞還是要先寫一寫基礎的題目

反思:1.pyhton裡面不可以用n--這種操作

    2.python的round函式有問題,對整數部分是奇數還是偶數有要求,不一定會進位,不如使用

         '%.2f'%temp_sum,確保變成浮點型