繁体   English   中英

使用python动态编程来赚钱

[英]Change money with python dynamic programming

这是两个用于找零钱的程序。 第一个只是获得所有组合的递归程序,第二个正在使用动态编程。 但是,当我进行第二个练习时,我遇到了麻烦。 它应该比第一个要快,但是我的程序会永远运行以完成它。 我很确定我正在使用动态编程,但是我不知道这是什么问题?

注意:总计是要更改的金额,单位是具有不同值的列表,存储的是用于存储步骤值的字典。

第一:

def changeMoney(total, units):
    if ( total == 0 ): 
        return [{}]
    elif ( total < 0 ):
        return []
    else:
        n = len(units)
        ret = []
        for i in range(0,n):
            sols = changeMoney(total-units[i],units[i:n])
            for sol in sols:
                if ( units[i] in sol ):
                    sol[units[i]] += 1
                else:
                    sol[units[i]] = 1
            ret.append(sol)
        return ret
print(dpChangeMoney(300,[100,50,20,10,5,2,1],{}))

第二:

import copy
def dpChangeMoney(total, units, stored):
    key = ".".join(map(str,[total] + units))
    if key in stored:
        return stored[key]
    else:
        if ( total == 0 ):
            return [{}]
        elif ( total < 0 ):
            return []
        else:
            n = len(units)
            for i in range(0,n):
                sols = copy.deepcopy(dpChangeMoney(total-
units[i],units[i:n], stored))
                for sol in sols:
                    if ( units[i] in sol ):
                        sol[units[i]] += 1
                    else:
                        sol[units[i]] = 1
                    if key in stored:
                        if sol not in stored[key]:
                            stored[key] += [sol]
                    else:
                        stored[key] = [sol]
        return stored[key]
print(dpChangeMoney(300,[100,50,20,10,5,2,1],{}))

这是一种更快的方法:

def dpChangeMoney(total, units, stored, min_ix=0):
    if total < 0:
        return []

    if total == 0:
        return [{}]

    if min_ix == len(units):
        return []

    key = (total, min_ix)
    if key in stored:
        return stored[key]

    sol_list = []
    u = units[min_ix]
    for c in range(total // u + 1):
        sols = dpChangeMoney(total - c*u, units, stored, min_ix + 1)
        for sol in sols:
            if c > 0:
                sol2 = sol.copy()
                sol2[u] = c
            else:
                sol2 = sol
            sol_list.append(sol2)

    stored[key] = sol_list
    return sol_list

如果按以下方式调用,则将打印指定情况下的解决方案数量:

print(len(dpChangeMoney(300, [100,50,20,10,5,2,1], {})))

结果是:

466800

在我的系统上,这花费了不到一秒钟的时间。 (当然,您可以打印实际的解决方案,但是有很多!)

要查看总共10的实际解决方案:

print(dpChangeMoney(10, [100,50,20,10,5,2,1], {}))

结果是:

[{1: 10}, {1: 8, 2: 1}, {1: 6, 2: 2}, {1: 4, 2: 3}, {1: 2, 2: 4}, {2: 5}, {1: 5, 5: 1}, {1: 3, 2: 1, 5: 1}, {1: 1, 2: 2, 5: 1}, {5: 2}, {10: 1}]

我只是想知道我的算法有什么问题。 在截止日期之后,我将更新更快的算法。 感谢您的建议和指示。 Ë

暂无
暂无

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

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