Python easy and concise 3 lines solution


  • 1
    class MapSum(object):
    
        def __init__(self): 
            self.d = {}
    
        def insert(self, key, val): 
            self.d[key] = val
    
        def sum(self, prefix):
            return sum(self.d[i] for i in self.d if i.startswith(prefix))
    

    Edited after Stefan's suggestion.


  • 0

    Ten characters shorter:

    def sum(self, prefix):
       #return sum([self.d[i] for i in self.d if i .startswith(prefix)] or [0])
        return sum(self.d[i] for i in self.d if i.startswith(prefix))
    

    Sad that this gets accepted, though. Even only takes about 40 ms. The test suite appears to be extremely weak.


Log in to reply
 

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