Python – How to write string into a matrix. Printing a matrix.

Writing string into a matrix seems like a non-interesting and somehow trivial task. Anyway, manipulating with matrices and strings in Python is actually somehow interesting, thus I have decided to present a small algorithmic challenge.  The task is pretty much like this:

Input

  • The input data should be read from the console. It consists of exactly two lines
  • On the first line, you’ll receive the dimensions of the stairs in format: “N M”, where N is the number of rows, and M is the number of columns. They’ll be separated by a single space
  • On the second line you’ll receive the string representing a snake, starting down from the top-left corner and slithering its way down. The first cell is filled with the first symbol of the snake, the second cell is filled with the second symbol, etc. The “snake” is as long as it takes in order to fill the box completely – if you reach the end of the string representing the snake, start again at the beginning.

Output

  • The output should be printed on the console. It should consist of N lines
  • Each line should contain a string representing the respective row of the matrix

Constraints

  • The dimensions N and M of the matrix will be integers in the range [1 … 12]
  • The snake will be a string with length in the range [1 … 20] and will not contain any whitespace characters

I have decided to use a matrix for the creation of the place, where the “snake” was supposed to be. In Python, this is a beautiful 1-liner with list comprehension:


Once the  matrix is created, we may easily loop through its rows and columns. I am using r for row and c for column in the code. The “tricky” part in the algorithm is actually to find which letter from the “snake” to write at a given position. The “remainder” in python helps us to calculate it quite easily – matrix[r][c] = snake[current_position % snake_size]. Every second line is “reversed”, thus matrix[r].reverse() is exactly the method that we need.

Printing a matrix

At the end, we need to print the matrix, and I have decided to make a separate function for it:

The whole code works quite ok, displaying the matrix filled with the given string in the given dimensions:

Enjoy your day! 🙂

Tagged with: , , , , ,