Search code examples
pythonperformancelistmatrixprocessing-efficiency

Find number of characters trapped in a list


My requirement here is to find number of '0' trapped between 'X' in a list most efficiently.

If you run the below code in Python:

def answer(heights):

    row = len(heights)
    col = max(heights)

    matrix = [['X' for j in range(i)] for i in heights]

    for i in range(col):

        rainWater = []

        for j in range(row):

            try:

                rainWater.append(matrix[j][i])

            except IndexError:

                rainWater.append('0')

        print rainWater

    return matrix

answer([1, 6, 5, 3, 2, 10, 4, 2, 6])

Output:

['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
['0', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
['0', 'X', 'X', 'X', '0', 'X', 'X', '0', 'X']
['0', 'X', 'X', '0', '0', 'X', 'X', '0', 'X']
['0', 'X', 'X', '0', '0', 'X', '0', '0', 'X']
['0', 'X', '0', '0', '0', 'X', '0', '0', 'X']
['0', '0', '0', '0', '0', 'X', '0', '0', '0']
['0', '0', '0', '0', '0', 'X', '0', '0', '0']
['0', '0', '0', '0', '0', 'X', '0', '0', '0']
['0', '0', '0', '0', '0', 'X', '0', '0', '0']

I need to find 'O' trapped between two 'X' most efficiently in Python. For example

['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']  
['0', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
['0', 'X', 'X', 'X', '0', 'X', 'X', '0', 'X']   --> 2 '0' are trapped
['0', 'X', 'X', '0', '0', 'X', 'X', '0', 'X']   --> 3 '0' are trapped
['0', 'X', 'X', '0', '0', 'X', '0', '0', 'X']   --> 4 '0' are trapped

Could anyone help me here how to solve this problem in Python?


Solution

  • My approach would be much simpler. Just count number of zeros within each row stripping out all the 0s at either end

    Implementation

    [''.join(row).strip('0').count('0') for row in matrix]
    

    Output

    >>> matrix = [['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
              ['0', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
              ['0', 'X', 'X', 'X', '0', 'X', 'X', '0', 'X'],
              ['0', 'X', 'X', '0', '0', 'X', 'X', '0', 'X'],
              ['0', 'X', 'X', '0', '0', 'X', '0', '0', 'X']] 
    >>> [''.join(row).strip('0').count('0') for row in matrix]
    [0, 0, 2, 3, 4]
    

    This is based on the logic that, if there exist any Zeros within any of the rows, and it is not at either end, that should be enclosed by 'X'.