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,确保变成浮点型


猜你喜欢

转载自www.cnblogs.com/captain-dl/p/10076497.html