This exercise combines comprehensions with range and a filter.
squares_up_to with one parameter, n. It returns the squares of 1 through n (inclusive) as a list, using a comprehension.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.
range(1, n + 1) inside the comprehension.% 2.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))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.