Python easy understand solution

  • 5
    class Excel(object):
        def __init__(self, H, W):
            self.M = [[{'v': 0, 'sum': None} for i in range(H)] for j in range(ord(W) - 64)]
        def set(self, r, c, v):
            self.M[r - 1][ord(c) - 65] = {'v': v, 'sum': None}
        def get(self, r, c):
            cell = self.M[r - 1][ord(c) - 65]
            if not cell['sum']: return cell['v']
            return sum(self.get(*pos) * cell['sum'][pos] for pos in cell['sum'])
        def sum(self, r, c, strs):
            self.M[r - 1][ord(c) - 65]['sum'] = self.parse(strs)
            return self.get(r, c)
        def parse(self, strs):
            c = collections.Counter()
            for s in strs:
                s, e = s.split(':')[0], s.split(':')[1] if ':' in s else s
                for i in range(int(s[1:]), int(e[1:]) + 1):
                    for j in range(ord(s[0]) - 64, ord(e[0]) - 64 + 1):
                        c[(i, chr(j + 64))] += 1
            return c

  • 0

    Seems like your self.m has the height and width reversed, curious as to why this works as I'm scratching my head to an error that I got for setting self.M=[{'v':0,'sum':None}]*(ord(W)-ord('A')+1)for _ in xrange(H)].

    If H:1, W='C', wouldn't you want [[{'sum': None, 'v': 0}, {'sum': None, 'v': 0}, {'sum': None, 'v': 0}]] instead of [[{'sum': None, 'v': 0}], [{'sum': None, 'v': 0}], [{'sum': None, 'v': 0}]] since this represents Excel:

  • 0

    @livelearn I think you are right. His self.M is confusing.

    Thanks @lee215 , really good approach. I didn't come up with a good solution for handling sum.

  • 0

    @livelearn @Free9 Thanks you are right.
    It should be like

    def __init__(self, H, W):
            self.M = [[{'v': 0, 'sum': None} for j in range(ord(W) - 64)] for i in range(H)]

    It happened to work in the other way just because the matrix was big enough.

Log in to reply

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