【问题标题】:Day 9 Secret Auction Program from 100 Days of Code with Dr. Angela Yu100 Days of Code 与 Angela Yu 博士的第 9 天秘密拍卖计划
【发布时间】:2022-11-16 19:22:39
【问题描述】:

有人可以帮我弄这个吗?我究竟做错了什么?我查看了Angela Yu博士的解决方案。她以不同的方式解决了这个问题,但我无法理解我在哪里犯了错误。

该程序应打印出价最高者的姓名和出价。但是,当我运行此代码时,控制台会打印出价和最后输入的名称。

from replit import clear
#HINT: You can call clear() to clear the output in the console.

from art import logo
print (logo)

game_end = False

bids = {}

while not game_end:

  name = input("What is your name?\n")
  bid = int(input("How much are you bidding? $"))
  
  bids[name] = bid
  game = input("Are there any other bidders. y or n\n").lower()
  
  if game == "n":
    game_end = True
    
  else:
    clear()
    
highest_bid = 0

for bidder in bids:
  if bid > highest_bid:
    highest_bid = bid
    winner = bidder
print(f"The winner is {winner} with a bid of ${highest_bid}")

【问题讨论】:

    标签: python dictionary replit


    【解决方案1】:

    您没有考虑存储在字典 bids 中的 bid 的值。您只需要在迭代时获取该值:

    for bidder, bid in bids.items():
      if bid > highest_bid:
        highest_bid = bid
        winner = bidder
    print(f"The winner is {winner} with a bid of ${highest_bid}")
    

    通过使用bids.items(),dict 会生成名称 (bidder) 和出价 (bid)

    或者,您可以对 bids 进行排序并提取最后(最高)出价:

    winner,highest_bid = sorted(bids.items(), key=lambda item:item[1])[-1]
    print(f"The winner is {winner} with a bid of ${highest_bid}")
    

    【讨论】:

    • 谢谢您的答复。我想告诉你,我在这方面几乎是个初学者。显然,您使用了项目功能。我不知道那是怎么回事。您还在 for 循环中使用了两个条目。我也不确定那是什么意思。 Angela 博士提到了她对这个问题的解决方案。你能告诉我她做了什么不同的事情让这个项目对她有用而不是对我有用吗?链接replit.com/@appbrewery/blind-auction-completed#main.py 中提到了她的代码。
    猜你喜欢
    • 2023-02-04
    • 2015-07-21
    • 2014-11-25
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多