实施最少的硬币量以备忘用?

问题描述

我正在练习动态编程的概念(递归不是我的强项)。我想知道如何改进我的代码,以便避免堆栈溢出。

任何帮助,谢谢!

def coinFlipping(n):
    """
    For n amount of change,return the minimal amount of currency in coins.

    Top-Down Approach (Memoization): Memo dictionary stores already solved
    subproblems to reuse and avoid recomputing. It's essentially recursion 
    but optimized to avoid recomputing results. 
    """
    COINS = {
        "penny": 0.01,"nickel": 0.05,"dime": 0.10,"quarter": 0.25,"dollar": 1.00
    }

    memo = {}

    def __coinFlipping(n):

        if n not in memo:
            # Base case (if n is equal to 0.01,0.05,0.10,0.25..)
            if n in COINS.values():
                memo[n] = 1
            else:
                results = []
                coins = (coin for coin in COINS.values() if coin < n)
                for coin in coins:
                    results.append(__coinFlipping(n - coin))
                memo[n] = 1 + min(results)
        else:
            return memo[n]         
    __coinFlipping(n)
    print(memo[n])

coinFlipping(10)

我获得了以下错误

File "/mnt/d/programs/algorithms/dynamicProgramming.py",line 45,in __coinFlipping
    results.append(__coinFlipping(n - coin))
  File "/mnt/d/programs/algorithms/dynamicProgramming.py",in __coinFlipping
    results.append(__coinFlipping(n - coin))
  [PrevIoUs line repeated 993 more times]
  File "/mnt/d/programs/algorithms/dynamicProgramming.py",line 44,in __coinFlipping
    for coin in coins:
  File "/mnt/d/programs/algorithms/dynamicProgramming.py",line 43,in <genexpr>
    coins = (coin for coin in COINS.values() if coin < n)
RecursionError: maximum recursion depth exceeded in comparison

解决方法

谢谢@user2864740@dannyadam

我将把我的最终代码留给以后查看该帖子的任何人。

def coinFlipping(n):
    """
    For n amount of cents,return the minimal amount of currency in coins.

    Top-Down Approach (Memoization): Memo dictionary stores already solved
    subproblems to reuse and avoid recomputing. It's essentially recursion 
    but optimized to avoid recomputing results. 
    """
    COINS = {
        "dollar": 100,"quarter": 25,"dime": 10,"nickel": 5,"penny": 1
    }

    memo = {}

    def __coinFlipping(change):

        if change not in memo:
            # Base case (if n is equal to 0.01,0.05,0.10,0.25..)
            if change in COINS.values():
                memo[change] = 1
            else:
                results = []
                coins = [coin for coin in COINS.values() if coin < change]
                for coin in coins:
                    results.append(__coinFlipping(change - coin))
                memo[change] = 1 + min(results)
        return memo[change]         
            
    __coinFlipping(n)
    print(memo[n])

coinFlipping(42)


实现此示例后,我开始认为这是一个不好的记忆示例。我本可以编写一个贪心算法来选择每一步中的最大价值硬币。例如从42c减去25c,从17c减去10c,依此类推,同时增加一个计数器。

,

user2864740发现了。更改为整数,代码开始运行。