创建一个计算系列之和的函数

时间:2017-10-16 03:07:33

标签: python python-3.x

#编写一个名为series_sum()的函数,提示用户输入非负数    #interger n。如果用户输入否定,则该函数应返回None    #否则函数应该返回以下系列的总和,    #1000 +(1/1)** 2 +(1/2)** 2 +(1/3)** 2 +(1/4)** 2 ... +(1 / n)** 2

SELECT id,
       NAME                               AS file_name,
       Sum(Datalength(data)) / 1048576.0  AS file_size,
       dbo.Fn_format_datetime(created_on) AS file_date
FROM   vessel_cert_attachment
WHERE  ( vessel_certificate_id = @vessel_certificate_id
          OR @vessel_certificate_id IS NULL )
GROUP  BY id,
          NAME,
          type,
          created_by,
          created_on 

3 个答案:

答案 0 :(得分:0)

完整功能:

def series_sum(n):
    if n >= 0:
        return 1000 + sum((1/x) ** 2 for x in range(1, n + 1))

或具有相同的功能,但明确否定否定:

def series_sum(n):
  if n >=0:
     return 1000 + sum((1/x) ** 2 for x in range(1, n + 1))  
  if n < 0:
     return None

答案 1 :(得分:0)

该函数需要一个参数,n。

Next ....对于sum ... range(1,n + 1)将创建一个从1到n的可迭代对象,您可以在for循环中使用它。在你的else语句下,创建一个变量&#39; total&#39; ..它从1000开始。对于1到n范围内的每个值,你将在平方值加总值上加1。

def series_sum():
     n = input("Please enter an integer greater than 0")
     n = int(n)
     if n < 0:
          return None
     else:
          numbers = range(1,n+1)
          total = 1000 
          for number in numbers:
               total = total + 1/n**2
          return total

答案 2 :(得分:-1)

def series_sum():
    n = input("Please enter a number greater than 0")
    if type(n,str):
        try:
            n = int(n)
        except:
            print 'enter integer value'
            return
    if n >=0:
        sum = 1000
        for i in range(1,n+1):
            sum += (1./i)**2
        return sum
    return