繁体   English   中英

此程序在python中的意外行为

[英]unexpected behaviour in this program in python

我有这段代码可以根据给定的总和列表计算总和的最小硬币数量。 例如: minimum change for 69 with denomiations [25,10,5,1] : [25, 25, 10, 5, 1, 1, 1, 1]minimum change for 69 with denomiations [25,10,5,1] : [25, 25, 10, 5, 1, 1, 1, 1]

def get_min_coin_configuration(sum=None, coins=None, cache={}):
    #if cache == None:  # this is quite crucial if its in the definition its presistent ...
    #    cache = {}
    if sum in cache:
        return cache[sum]
    elif sum in coins:  # if sum in coins, nothing to do but return.
        cache[sum] = [sum]
        return cache[sum]
    elif min(coins) > sum:  # if the largest coin is greater then the sum, there's nothing we can do.
        #cache[sum] = []
        #return cache[sum]
        return []
    else:  # check for each coin, keep track of the minimun configuration, then return it.
        min_length = 0
        min_configuration = []
        for coin in coins:
            results = get_min_coin_configuration(sum - coin, coins, cache)
            if results != []:
                if min_length == 0 or (1 + len(results)) < len(min_configuration):
                    #print "min config", min_configuration
                    min_configuration = [coin] + results
                    #print "min config", min_configuration
                    min_length = len(min_configuration)
                    cache[sum] = min_configuration
        return cache[sum]
if __name__ == "__main__":
    print "minimum change for 69 with denomiations [25,10,5,1] by recursive : ",get_min_coin_configuration(69,[25,10,5,1])
    print "*"*45
    print "minimum change for 7 with denomiations [4,3,1] by recursive : ",get_min_coin_configuration(7,[4,3,1])

当我注释掉主菜单中的任何一条打印语句时,该程序似乎运行良好。 当我同时调用两个函数时,它打印错误。 注释掉主体中的两个打印语句,您会看到它正确地打印了最少的硬币。

minimum change for 69 with denomiations [25,10,5,1] by recursive :  [25, 25, 10, 5, 1, 1, 1, 1]
*********************************************
minimum change for 7 with denomiations [4,3,1] by recursive :  [5, 1, 1]
if __name__ == "__main__":
    cache_denom_set1 = {}
    cache_denom_set2 = {}
    print "minimum change for 69 with denomiations [25,10,5,1] by recursive : ",get_min_coin_configuration(69,[25,10,5,1],cache_denom_set1)
    print "*"*45
    print "minimum change for 7 with denomiations [4,3,1] by recursive : ",get_min_coin_configuration(7,[4,3,1],cache_denom_set2)

为每个面额传递单独的缓存

问题是您的缓存已经知道如何将7更改为5,1,1,因此它只返回...缓存不知道面额集中不再有5 ...

字典是可变的,如列表...这应该证明问题

def dict_fn(cache={}):
    cache[len(cache.keys())] = 1
    print cache

dict_fn()
dict_fn()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM