示例#1
0
    def test_reduce_sum_keys(self):
        """
        simple test to reduce a dictionary to the sum of its keys
        """
        dictionary = {
                        1: { 2: {}, 3: {} },
                        2: { 4: {}, 6: {} },
                     }

        
        # filter out the odd elements
        actual = dicttools.reduce(lambda acc, key, _: acc + key, dictionary, 0)
        self.assertEquals(18, actual, msg="%s != %s" % (actual, 18))
示例#2
0
    def test_reduce_performance(self):
        total = 3000000
        items = [ (x, float(x)) for x in range(0, total) ]
        dictionary = dict(items)

        start = time.time()
        dicttools.reduce(lambda acc, x, y: acc + x, dictionary, initializer=0)
        dictionary_elapsed = time.time() - start

        start = time.time()
        reduce(lambda acc, (x,y): acc + x, items, 0)
        list_elapsed = time.time() - start

        print('\n dict reduce is %2.2fx slower than list reduce' % \
                                             (dictionary_elapsed/list_elapsed))

        start = time.time()
        dicttools.reduce(lambda acc, x, y: acc + x,
                         dictionary,
                         initializer=0,
                         recursive = False)
        dictionary_elapsed = time.time() - start
        print(' dict reduce(recursive=False) is %2.2fx slower than list reduce' % \
                                             (dictionary_elapsed/list_elapsed))
示例#3
0
    def test_reduce_calculate_debt(self):
        """
        reduce a dictionary of user transactions to the amount owed by all 
        users
        """
        dictionary = {
                        'user1': { 'transactions' : [ -100, 50, 25 ] },
                        'user2': { 'transactions' : [ -200, 200, -100 ] },
                     }
        
        def calculate_debt(acc, key, value):
            """
            calculate from the various transactions the current debt of all 
            users
            """
            if key == 'transactions':
                for amount in value:
                    acc += amount 

            return acc
        
        # filter out the odd elements
        actual = dicttools.reduce(calculate_debt, dictionary, 0)
        self.assertEquals(-125, actual, msg="%s != %s" % (actual, -125))