簡體   English   中英

利用遞歸僅返回基本情況的優化問題(Python)

[英]Optimization problem utilizing recursion only returning base case (Python)

我正在處理的這段代碼有問題。 該問題在代碼的文檔字符串中進行了概述。 我的 function 不斷返回遞歸算法的基本情況而不是最佳解決方案,但我不知道為什么。 這是代碼:

###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise

#================================
# Part B: Golden Eggs
#================================

# Problem 1
def dp_make_weight(egg_weights, target_weight, memo = {}):
    """
    Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
    an infinite supply of eggs of each weight, and there is always a egg of value 1.

    Parameters:
    egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
    target_weight - int, amount of weight we want to find eggs to fit
    memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)

    Returns: int, smallest number of eggs needed to make target weight
    """
    # TODO: Your code here
    #sort eggs by biggest to smallest
    egg_weights = sorted(egg_weights,reverse=True)
    #base case
    if target_weight == 0 or egg_weights == []:
        num_eggs = 0


    #start by taking the biggest egg, if you cant go right (move on)
    elif target_weight - egg_weights[0] < 0:
        num_eggs = dp_make_weight(egg_weights[1:],target_weight)
    #if u can take the egg, take it
    else:
        num_eggs = dp_make_weight(egg_weights,target_weight-egg_weights[0])
    return num_eggs






# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
    egg_weights = (1,5,10,25)
    n = 99
    print("Egg weights = (1, 5, 10, 25)")
    print("n = 99")
    print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
    print("Actual output:", dp_make_weight(egg_weights, n))
    print()

#what i am getting 
# Egg weights = (1, 5, 10, 25)
# n = 99
# Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)
# Actual output: 0

問題是當你取一個雞蛋時,你並沒有增加雞蛋的數量。

要修復替換:

num_eggs = dp_make_weight(egg_weights,target_weight-egg_weights[0])

num_eggs = 1 + dp_make_weight(egg_weights,target_weight-egg_weights[0])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM