This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Applied problem solving

Triangle list

face Josiah Wang

This challenge is just a variant of one of the triangle patterns from earlier, except it should now be a function that returns a nested list instead of just printing out triangles.

Write a function named generate_triangle_list() that takes an integer length as input. The function should return a nested list with the given length, and each element in the list is a list containing the integers from 1 to the current ‘row’ number (inclusive).

For example, if the input length is 5, then the function should return [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]].

Remember to test the correctness of your function!

Sample inputs and outputs

Example 1

  • Input: 3
  • Returns: [[1], [1, 2], [1, 2, 3]]

Example 2

  • Input: 6
  • Returns: [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]]

Example 3

  • Input: 1
  • Returns: [[1]]

Example 4

  • Input: 0
  • Returns: []