[英]How to convert an Iterative Function to a Recursive one in python
我寫了一個迭代的 function 來解決背包問題的一個非常簡化的版本,它在下面給出。
迭代代碼
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)
現在我還需要以遞歸格式編寫相同的 function 並且我不知道如何做到這一點。 我已經編寫了以下代碼,但它沒有給我正確的答案。 誰能幫我更正代碼?
遞歸代碼
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()
將下一個產品從列表中刪除,然后將剩余的列表傳遞給 function 的下一個調用。 一個空的product_list
是結束遞歸的觸發器。 注意:由於您需要每個產品的left
累積值,因此您也可以將其作為參數轉發。 最初,left 應該是None
,這可以通過使用其默認值來完成。
注意:為簡單起見,我制作了一個獨立的 function,但它也可以實現為 class 方法。
例子:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.