itertools galore


  • 1

    Using four different itertools tools. I'm particularly delighted with compress(count(), row) to get the indices of the ones, it looks so nice and I rarely get to use those two tools. Based on @lee215's solution. Gets accepted in about 850 ms.

    def countCornerRectangles(self, grid):
        d = collections.Counter(
                itertools.chain.from_iterable(
                    itertools.combinations(
                        itertools.compress(
                            itertools.count(),
                            row
                        ),
                        2
                    )
                    for row in grid
                )
            )
        return sum(x * (x - 1) / 2 for x in d.values())
    

    Shorter version:

    from collections import Counter
    from itertools import *
    
    class Solution(object):
        def countCornerRectangles(self, grid):
            d = Counter(chain(*(combinations(compress(count(), row), 2) for row in grid)))
            return sum(x * (x - 1) / 2 for x in d.values())
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.