[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."
Solution:
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:
Remarks:
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."
Solution:
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum_of_squares(n): | |
result = 0 | |
for i in range(1, n): | |
result += i**2 | |
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum_of_squares(n): | |
return sum([i**2 for i in range(n)]) |
- 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.