Practice: Squares

Practice: Squares

This exercise combines comprehensions with range and a filter.

Exercise

  1. Define a function named squares_up_to with one parameter, n. It returns the squares of 1 through n (inclusive) as a list, using a comprehension.
  2. Define a function named even_squares_up_to with one parameter, n. It returns only the squares that are even, using a comprehension with an if.

squares_up_to(5) returns [1, 4, 9, 16, 25]. even_squares_up_to(5) returns [4, 16].

Run your code to see the output, then press Submit.

Hints

  • range(1, n + 1) inside the comprehension.
  • For the second function, filter on the square being even — % 2.

Tests

import unittest


class TestSquares(unittest.TestCase):
    def test_squares_up_to_5(self):
        self.assertEqual(squares_up_to(5), [1, 4, 9, 16, 25])

    def test_squares_up_to_1(self):
        self.assertEqual(squares_up_to(1), [1])

    def test_squares_up_to_0_is_empty(self):
        self.assertEqual(squares_up_to(0), [])

    def test_even_squares_up_to_5(self):
        self.assertEqual(even_squares_up_to(5), [4, 16])

    def test_even_squares_up_to_1_is_empty(self):
        self.assertEqual(even_squares_up_to(1), [])
def squares_up_to(n):
    return [i ** 2 for i in range(1, n + 1)]


def even_squares_up_to(n):
    return [i ** 2 for i in range(1, n + 1) if (i ** 2) % 2 == 0]


print(squares_up_to(5))
print(even_squares_up_to(5))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.