如果您不想在列表中花费内存,只需将maximun保存在一个变量中,并将其与每次迭代中生成的值进行竞争。在maxProfit = float("-inf") # First contendant is -Infinity, a real low number
for NP in range(MP, MaxP+1, 10):
CostofTicket = TP - (((NP - MP)/10)*.5)
Gross = NP * CostofTicket
Profit = (NP * CostofTicket) - FixedCost
if Profit > maxProfit: # Here is the Fight. Winner stays with the trophy "maxProfit"
maxProfit = Profit
print (NP, end=" ")
print ("$", format(CostofTicket, "3,.2f"), end=" ")
print ("$", format(Gross, "3,.2f"), end=" ")
print ("$", format(FixedCost, "3,.2f"), end=" ")
print ("$", format(Profit, "3,.2f"))
print ("Maximum Profit: ", end="")
print (format(maxProfit, "3,.2f")) # And the winer is...
print ("Maximum Profit Ticket Price: ")
print ("Maximum Profit Number of Passengers: ")
这段代码不使用内存(一个列表),并让您直观地了解所提到的max函数是如何实现的。在
您还可以避免在生成器中使用内存:
^{pr2}$
你会明白的。在