163k views
5 votes
Define a function below called nested_list_string. The function should take a single argument, a list of lists of numbers. Complete the function so that it returns a string representation of the 2D grid of numbers. The representation should put each nested list on its own row. For example, given the input [[1,2,3], [4,5,6]] your function should produce the following string: "1 2 3 \\4 5 6 \\" Hint: You will likely need two for loops.

User AnGG
by
6.5k points

1 Answer

3 votes

Answer:

The solution code is written in Python:

  1. def nested_list_string(list2D):
  2. output = ""
  3. for i in range(0, len(list2D)):
  4. for j in range(0, len(list2D[i])):
  5. output += str(list2D[i][j]) + " "
  6. return output

Step-by-step explanation:

Let's create a function and name it as nested_list_string() with one input parameter, list2D (Line 1).

Since our expected final output is a string of number and therefore we define a variable, output, to hold the string (Line 2).

Next use two for loops to traverse every number in the list and convert each of the number to string using str() method. Join each of individual string number to the output (Line 3-5).

At the end, we return the output (Line 7)

User Nick Duddy
by
6.0k points