Python – Matrix calculation – Problem

This week I have started to study Python a little more into detail in the courses of HackBulgaria. After end of the second day, the last problem was considered worthy for blogging, as far as it took me about an hour (or less) to come up with a solution.

nYSff

Anyway, the problem was not that difficult, the difficulty was that I am somehow reluctant to work with dictionaries, especially when the key to the dictionary is a tuplet. Enough speaking, here comes the description of the problem, taken from here:


Matrix Calculation

You are given a NxM matrix of integer numbers.

We can drop a bomb at any place in the matrix, which has the following effect:

  • All of the 3 to 8 neighbours (depending on where you hit!) of the target are reduced by the value of the target.
  • Numbers can be reduced only to 0 – they cannot go to negative.

For example, if we have the following matrix:

and we drop at 9, this will result in the following matrix:

Implement a function called matrix_bombing_plan(m).

The function should return a dictionary where keys are positions in the matrix, represented as tuples, and values are the total sum of the elements of the matrix, after the droping at that position.

The positions are the standard indexes, starting from (0, 0)

For example if we have the following matrix:

and run the function, we will have:

We can see that if we drop at(1, 1) or (2, 1), we will do the most damage!


So, after some analysis, this is what I realized:

    1. We should make the function work with any size of a matrix;
    2. We should give as  an imput the matrix;
    3. We should calculate the boundaries of the given matrix;
    4. I should find a way to be able to reach the values in the dictionary and change them;
    5. I should use 3 different dictionaries – one for the input, one for the calculation of every single case, one for the output;
    6. The one for the calculation for every single case should be rewritten with new values every time, thus  I need to know how to erase a dictionary in Python;
    7. It could be a good idea to make a function, returning me a 0 for each negative value;
    8. Enough 🙂

Did it work? Check out by yourself:

matrix_problem

So, how did I did it? Here comes the code:

Update – it is possible not to use the function “zero_if_negative”, but to loop over the dictionary lTempResult[] and assign to zero each negative value, like this:

Enjoy it 🙂

Tagged with: , ,