相关疑难解决方法(0)

记住硬币变化

我想将我的硬币更改功能转换为memoized函数
来做到这一点,我决定使用字典,以便我的dict中的一个键将成为硬币,值将是一个包含所有可以更改"键"的硬币的列表硬币.
我做的是:

def change(a,kinds=(50,20,10,5,1)):
    if(a==0):
            return 1
    if(a<0 or len(kinds)==0):
            return 0

    return change(a-kinds[0],kinds)+change(a,kinds[1:])


def memoizeChange(f):
    cache={}
    def memo(a,kinds=(50,20,10,5,1)):

        if len(cache)>0 and kinds in cache[a]:
            return 1
        else:
            if(f(a,kinds)==1):
                cache[a]=kinds // or maybe cache[a].append(..)
                return cache[a]+memo(a-kinds[0],kinds)+memo(a,kinds[1:])
    return memo

memC=memoizeChange(change)
kinds=(50,20,10,5,1)
print(memC(10,kinds))
Run Code Online (Sandbox Code Playgroud)

我想得到一些建议,或者可能还有另一种方法可以做到这一点.
谢谢.


编辑
记忆版:

def change(a,kinds=(50,20,10,5,1)):
    if(a==0):
            return 1
    if(a<0 or len(kinds)==0):
            return 0
    return change(a-kinds[0],kinds)+change(a,kinds[1:])


def memoizeChange(f):
    cache={}
    def memo(a,kinds=(50,20,10,5,1)):
        if not (a,kinds) in cache:
                cache[(a,kinds)]=f(a,kinds)
        return cache[(a,kinds)]
    return memo

change=memoizeChange(change)
print(change(10))
Run Code Online (Sandbox Code Playgroud)

python memoization

2
推荐指数
1
解决办法
2256
查看次数

标签 统计

memoization ×1

python ×1