<p>您设置程序以尝试每个选项的方式是违反直觉的。如果你先对列表排序,你只需要浏览列表一次,而不是每次都从头开始重试。您只需将<code>outfits=sorted(outfits)</code>放在开头就可以做到这一点。
这消除了对大多数代码的需要,因为最便宜的选项总是第一个</p>
<p>你可以做的另一个改进是,你实际上不需要记录花费和结果之类的事情。因为你唯一关心的是你能买多少东西,所以你可以创建一个变量(从0开始),每次你能买得起另一件东西的时候,给它加上1</p>
<p>另一个可能的改进是,不必每次都检查,你只需把钱当作“余额”,然后从总数中减去你花的钱,直到钱少于0为止</p>
<p>作为一个快速的侧重点,而不是写作</p>
<pre><code>for i in len(outfits):
spent+=outfits[i]
</code></pre>
<p>您可以遍历列表本身</p>
<pre><code>for i in outfits:
spent+=i
</code></pre>
<p>得到同样的结果</p>
<p>您的最终代码应该如下所示:</p>
<pre><code>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
</code></pre>
<p>任何问题都可以问;)</p>