[DSA in Python] sum_of_squares.py

This was the fourth exercise of Chapter 1 (Python Primer) in the book 'Data Structures and Algorithms in Python' by Goodrich et al.

Problem: "Write a short Python function that takes a positive integer n and returns the sum of the squares of all the positive integers smaller than n."

The solution is very straightforward. We want to take all the numbers that are less than n and then square each of the numbers. We then take these squared numbers and add them all up.
We can also use list comprehension and Python's built-in function sum to make the code shorter:

  • Comprehension provides a short way of constructing sequences such as lists, sets, dictionaries, and so on. 
    • Let's say we want to create a list consisting of numbers up to, but not including, n
    • Let n = 5, then we can create a list like so: m = [1, 2, 3, 4]
      • We set variable m to hold a list
    • However, we can also write it like so: m = [i for i in range(n)], where n = 5
      • As we can see, we can easily change n to be something else besides 5. 
  • You can read more about comprehensions here.