首页 > 解决方案 > 如何在python中将迭代函数转换为递归函数

问题描述

我编写了一个迭代函数来解决背包问题的一个非常简化的版本,如下所示。

迭代代码

def so_rich(self, money):
        """ Find the minimum amount left from the given 'money' after buying s series of products """

        # suppose you haven't seen any product yet
        # the only possible amount of money left is "money"
        # this is a set to record the possible money left
        left = set([money])
        # get products
        lst = list(self.warehouse.inventory.values())
        for product in lst:
            
            # a temporary set to save the updates of "left"
            # you don't want to modify the set you're iterating through
            tmp_left = set()
            # update tmp_left
            for m in left:
                
                if type(product) != Limited_Product:
                    new_left = m
                    while new_left >= product.price:
                        new_left = new_left - product.price
                        tmp_left.add(new_left)
                else:
                    # handle limited product
                    new_left = m
                    product_count = product.amount
                    while new_left >= product.price and product_count > 0:
                        new_left = new_left - product.price
                        tmp_left.add(new_left)
                        product_count -= 1
                        
            left.update(tmp_left)
        return min(left)

现在我还需要以递归格式编写相同的函数,但我不知道如何做到这一点。我已经编写了以下代码,但它没有给我正确的答案。谁能帮我更正代码?

递归代码

def so_rich_recursive(self, money):
        """ recursively find the minimum amount left from the given 'money' after buying s series of products """
        # YOUR CODE GOES HERE #

        # get products
        lst = list(self.warehouse.inventory.values())
        
        def helper(lst, money):
            # base case
            if not lst:
                return money

            cur_min = money
            product = lst[0]
            print(product)
            print(cur_min)
            if type(product) != Limited_Product:
                tmp = money
                while tmp >= product.price:
                    print(product.name, tmp)
                    tmp = tmp - product.price
            else:
                tmp = money
                product_count = product.amount
                while tmp >= product.price and product_count > 0:
                    print(product.name, tmp)
                    tmp = tmp - product.price
                    product_count -= 1
            cur_min = tmp
            lst.pop(0)
            return helper(lst, min(money, cur_min))
            
        
        return helper(lst, money)

标签: pythonpython-3.xrecursionknapsack-problem

解决方案


考虑它的一种方法是从使用递归替换for product in lst:循环的想法开始。为此,可以使用pop()从列表中取出下一个产品,然后将剩余的列表传递给函数的下一个调用。空product_list是结束递归的触发器。注意:由于您需要left每个产品的累积值,因此您也可以将其作为参数转发。最初,left 应该是None可以通过使用其默认值来完成的。

注意:为了简单起见,我做了一个独立的函数,但它也可以实现为类方法。

例子:

def so_rich_recursive(product_list, money, left=None):

    if not product_list:
        return min(left)

    product = product_list.pop()
    if not left:
        left = set([money])
        
    tmp_left = set()
    # update tmp_left
    for m in left:
                
        if type(product) != Limited_Product:
            new_left = m
            while new_left >= product.price:
                new_left = new_left - product.price
                tmp_left.add(new_left)
        else:
            # handle limited product
            new_left = m
            product_count = product.amount
            while new_left >= product.price and product_count > 0:
                new_left = new_left - product.price
                tmp_left.add(new_left)
                product_count -= 1

    left.update(tmp_left)
    return so_rich_recursive(product_list, money, left)

推荐阅读