简体   繁体   中英

Sum of squares function

I'm trying to code the sum of squares in python and I'm pretty new to this.

This is what I have for now:

n=int(input("n="))

def sumsquare(n):
    sum=0
    i=0
    while(n<=i):
        sum= sum + i**2
        i= i+1
    return sum

Basically what I'm trying to do is to make the user choose a number, and based on that number I want to calculate the sum of squares, and return "The sum of square is ___"

pythonic方式是sum(x ** 2 for x in range(1, n + 1))

n=int(input("n="))

def sumsquare(n):
    sum=0
    i=0
    while(i<=n):
        sum= sum + i**2
        i += 1
    return sum

# print(sumsquare(n))
print('the sum of square is {}'.format(sumsquare(n)))

for your reference.

您可以将函数pow映射到rangesum

print(sum(map(lambda x: pow(x, 2), range(n+1))))
def square(n):
   return n*n

def sum_squares(x):
   sum = 0
   for n in range(x):
      sum += square(n)
   return sum

print(sum_squares(10)) 

//should be answer 285

this is the answer of your question .

You can just use square() and also return the integer output like this. The O/P would be the sum of the squares of the range you are going to provide:

#Returns Square of N
def square(n):
    return n*n

def sum_squares(x):
    sum = 0
    for n in range(x):      #loops through the range of X
        sum += int(square(n)) #calling for the square of N making sure it is in integer format                           
    return sum

print(sum_squares(10)) #285
print(sum_squares(3)) #14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM