Python generator1 + generator2

We can not add two generators together by using generator1 + generator2, we should use itertools.chain instead.

Example problem

Solution

class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
grid_r = ['0'+''.join(str(r) for r in row)+'0' for row in grid]
grid_c = ['0'+''.join(str(c) for c in col)+'0' for col in zip(*grid)]
return sum(row.count('01')+row.count('10') for row in grid_r+grid_c)

The above code has the space complexity of O(RC) where R is the number of rows and C is the number of columns. We can further reduce the space complexity by using a generator. Since generator1+generator2 will get an error, we should use itertools.chain instead.

from itertools import chain
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
grid_r = ('0'+''.join(str(r) for r in row)+'0' for row in grid)
grid_c = ('0'+''.join(str(c) for c in col)+'0' for col in zip(*grid))
return sum(row.count('01')+row.count('10')
for row in chain(grid_r, grid_c))

It is very interesting that there is no significant difference of memory using for the above two solutions based on this problem, although the latter one is supposed to be more memory efficient.

Data Scientist/MLE/SWE @takemobi