Python Question:
Write a function which returns the sum of squares of the integers 1 to n. For example, the sum of the squares from 1 to 4 is 1 + 4 + 9 + 16, or 30. You may choose what should be returned if n == 0
You may not use the built-in Python sum function.
The Solution Must be recursive
>>> sum_of_squares(1)
1
>>> sum_of_squares(4)
30
>>> sum_of_squares(8) # 64 + 49 + 36 + ... + 4 + 1
17650828
test.py
# Tester program for the Plan-Composition Study Problems
from sumofsquares import sumOfSquares
print( sumOfSquares( 4 ) )
sumofsquares.py
# Sum of Squares
"""
Design a program sumOfSquares that consumes an integer n and
produces
the sum of the squares of all numbers from 1 through n.
You may assume that n is at least 1.
Example: sumOfSquares(4) yields 30
"""
def sumOfSquares( n ) :
# Initialize helper variables
sum_of_squares = 0
# Go through all integers from 1 until n
for x in range( 1, ( n + 1 ) ) :
# Add x^2 to the running sum
sum_of_squares += ( x ** 2 )
return sum_of_squares
Get Answers For Free
Most questions answered within 1 hours.