如何解决如何在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)
解决方法
考虑它的一种方法是从您将使用递归替换 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,left)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。