与for循环python中的最大值相关的值

时间:2016-03-14 02:55:17

标签: python for-loop max

我现在能够在for循环中打印最大利润值,但我还需要打印与乘客数量相关的值以及允许它为最大值的票证值。我无法弄清楚如何打印这些值。

Loop = "y"
FixedCost = 2500

while Loop == "y":

输入

    MP = int(input("1 of 3 - Enter the minimum number of passengers: "))
    print ("The minimum number of passengers is set to ", MP)

    MaxP = int(input("2 of 3 - Enter the maximum number of passengers: "))
    print ("The minimum number of passengers is set to ", MaxP)

    TP = float(input("3 of 3 - Enter the ticket price: "))

for循环中以下打印的标题

    print ("Number of", end="    ")
    print ("Ticket")
    print ("Passengers", end="   ")
    print ("Price", end="             ")
    print ("Gross", end="              ")
    print ("Fixed Cost", end="          ")
    print ("Profit")

For Loop

    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 (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"))

打印最大值和相关值

    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: ")

    Loop = str(input("Run this contract again (Y or N): "))

1 个答案:

答案 0 :(得分:1)

max(以及一般排序)适用于tuplelist等集合以及整数。只需使用tuple作为第一项以及您想要与之关联的任何其他内容构建Profit,并使用它代替Profit本身。

我不确定你想要保留的循环中的哪些变量,所以我只是飞了起来......

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, TP, NP, MP))

    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"))

# find max profits tuple and unpack its values
Profit, TP, NP, MP = max(profits)
# etc...