for循环python中的最大值

时间:2016-03-14 01:24:29

标签: python for-loop max

我一直在试图弄清楚如何从for循环中打印最大值。这是我的家庭作业所必需的。我尝试过使用max函数,但我一直在使用

parsed.products[0]

TypeError: unorderable types: str() > float()

2 个答案:

答案 0 :(得分:0)

max确实是你想要的。您获得的TypeError是因为您像对format()的来电一样对待它。相反,为了方便起见,将这些步骤分开并将结果赋予max名称。

profits = []
for NP in range(MP, MaxP+1, 10):

        CostofTicket = TP - (((NP - MP)/10)*.5)
        Gross = NP * CostofTicket
        Profit = (NP * CostofTicket) - FixedCost
        profits.append(Profit)

    # ... print()s ...    


    greatest_profit = max(profits)
    print ("Maximum Profit: ", end="")
    print (format(greatest_profit, "3,.2f"))
    print ("Maximum Profit Ticket Price: ")
    print ("Maximum Profit Number of Passengers: ")

答案 1 :(得分:0)

如果您不想在列表中花费内存,只需将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函数是如何实现的。

您还可以避免使用带生成器的内存:

import operator

def ticket_values(MP, MaxP, TP, FixedCost):
    for NP in range(MP, MaxP+1, 10):
        CostofTicket = TP - (((NP - MP)/10)*.5)
        Gross = NP * CostofTicket
        Profit = (NP * CostofTicket) - FixedCost
        yield (NP, CostofTicket, Gross, Profit)

for ticket_value in ticket_values(MP, MaxP, TP, FixedCost):
    print (ticket_value[0], end="          ")
    print ("$", format(ticket_value[1], "3,.2f"), end="          ")
    print ("$", format(ticket_value[2], "3,.2f"), end="          ")
    print ("$", format(FixedCost, "3,.2f"), end="          ")
    print ("$", format(ticket_value[3], "3,.2f"))

print ("Maximum Profit: ", end="")
print (format(max(ticket_values(MP, MaxP, TP, FixedCost), key=operator.itemgetter(3))[3], "3,.2f"))
print ("Maximum Profit Ticket Price: ")
print ("Maximum Profit Number of Passengers: ")

你会明白这一点。