2 回答

TA貢獻1805條經驗 獲得超9個贊
在運行循環之前,將價格從最小到最大排序。對于您的示例,它先添加 2,然后添加 3,然后添加 5,發現大于 7,因此返回 2。如果按順序排列,則會添加 1、2 和 3,然后再添加到 5。

TA貢獻1812條經驗 獲得超5個贊
您設置程序來嘗試每個選項的方式是違反直覺的。如果先對列表進行排序,則無需每次都從頭開始重試,只需瀏覽列表一次。您可以通過在開始處放置 來非常簡單地完成此操作outfits=sorted(outfits)。這消除了對大部分代碼的需求,因為最便宜的選項永遠是第一個。
您可以做出的另一個改進是,您實際上不需要跟蹤諸如花費和結果之類的事情。由于您唯一關心的是您可以購買多少商品,因此您可以創建一個變量(從 0 開始),并在每次您買得起另一件商品時為其添加 1。
另一個可能的改進是,您不必每次都檢查,if spent<money只需將錢視為“余額”,然后從總數中減去您花費的金額,直到錢小于 0。
只是作為一個快速的側面觀點,而不是寫
for i in len(outfits):
spent+=outfits[i]
您可以迭代列表本身
for i in outfits:
spent+=i
并得到相同的結果
您的最終代碼應該如下所示:
def getMaximumOutfits(money,outfits):
outfits=sorted(outfits)#sorts the list from smallest --> biggest
items=0
max_size=0
for i in outfits: #goes through each element in the outfit list
money-=i #subtracts the cost of this item from the remaining money
if money<0: #if they couldn't afford this item
max_size=items #the amount of items they had before this one is their max
else: #if they can afford this item
items+=1 #the total items goes up by 1
return(max_size)
print(getMaximumOutfits(7,[2,3,5,1]))
>>> 3
有任何問題請隨時詢問我(們 ;)
添加回答
舉報