用python实现零钱找零的三种方法

发布时间:2019-09-24 08:34:56编辑:auto阅读(3022)

    1.递归(recursion)

    def coins_changeREC(coin_values, change):
        """
        递归实现零钱找零
        """
        min_count = change 
        # base case
        if change in coin_values:
            return 1
        for value in [i for i in coin_values if i <= change]:
            count = 1 + coins_changeREC(coin_values, change-value)
            if count < min_count:
                min_count = count
        return min_count

    2.添加caching的递归

    def coins_changeREC_cache(coin_values, change, known_counts=None):
        """
        添加了caching的递归零钱找零,
        用空间换时间
        """
        if known_counts == None:
            known_counts = [0] * (change + 1) # why plus 1? think!
        min_count = change
        # base case
        if change in coin_values:
            return 1
        elif known_counts[change] > 0:
            return known_counts[change]
        for value in [i for i in coin_values if i <= change]:
            count = 1 + coins_changeREC_cache(coin_values,
                                              change-value,
                                              known_counts)
            if count < min_count:
                min_count = count
        known_counts[change] = min_count
        return min_count

    3.动态规划(Dynamic Programming)

    def coins_changeDP(coin_values, change, min_counts=None, last_used_coins=None):
        """
        利用动态规划(Dynamic Programming)的思想实现零钱找零
        """
        if min_counts == None:
            min_counts = [0] * (change + 1)
        if last_used_coins == None:
            last_used_coins = [0] * (change + 1)
    
        for cents in range(change + 1):
            min_count = cents
            for value in [i for i in coin_values if i <= cents]:
                if 1 + min_counts[cents-value] < min_count:
                    min_count = 1 + min_counts[cents-value]
                    last_used_coins[cents] = value
            min_counts[cents] = min_count
    
        return min_counts[-1], print_coins(change, last_used_coins)
    
    def print_coins(change, last_used_coins):
        used_coins = []
        while change > 0:
            used_coins.append(str(last_used_coins[change]))
            change = change - last_used_coins[change]
        return ','.join(used_coins)

    最后测试三种方法实现的零钱找零的时间效率:

    def main():
        import timeit
        value_list = [1, 5, 10, 25]
        t1 = timeit.Timer('coins_changeREC(%s,%s)'%(value_list, 63),'from __main__ import coins_changeREC, main')
        t2 = timeit.Timer('coins_changeREC_cache(%s,%s)'%(value_list, 63),'from __main__ import coins_changeREC_cache, main')
        t3 = timeit.Timer('coins_changeDP(%s,%s)'%(value_list, 63),'from __main__ import coins_changeDP, main')
        print(t1.timeit(number=1))
        print(t2.timeit(number=1))
        print(t3.timeit(number=1))
    
    main()

    结果显示:
    这里写图片描述
    第一种没有添加caching的递归实现,完成一次63分零钱的找零竟然需要60s,简直无法忍受。
    而添加了caching的递归,一次找零0.22ms就完成了,这是生动的用空间换时间的算法。而采用DP思想的算法,0.14ms就完成了。

关键字