Trip to Python

딕셔너리와 반복문의 활용

Kestrel 2022. 11. 27. 14:21

강좌에서 이번 미션은 경매 프로그램이었다. 이름과 비딩 금액을 넣고 가장 높은 비딩을 한 사람의 이름과 비딩 금액을 출력시키는 것으로 글로 쓰는건 참 쉬운데 코딩은 어려웠다. 어려웠던 점을 기록하여 후에 참고 하도록 한다.

 

<정답 코드>

* 아쉽지만 내 코드가 다 날라가서 정답 코드만 적게 되었다....

 

from replit import clear
from art import logo
print(logo)

bids = {} * 이렇게 빈 딕셔너리를 먼저 생성하고 코딩하는게 아직 익숙하지가 않다.
bidding_finished = False * 이것 역시 while문을 생성할 때 선생님은 이렇게 하시는데 난 직접 조건을 적었다. 이게 좀 가시성이 있는 것 같기두 하다.

def find_highest_bidder(bidding_record):
  highest_bid = 0 * 내가 for 문에서 항상 어려워 하는 빈 값 설정, 
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:
    bid_amount = bidding_record[bidder]  *여기서 떠올리기 쉽지 않았던 것은 이미 딕셔너리를 앞 전에 규정하지 않았는데 가정하고 for 문을 구성하고 bid_mount를 value로 설정하였다. 이렇게 짜는게 낮설었다. 
    if bid_amount > highest_bid: 
      highest_bid = bid_amount  * 높은 값이 highest_bid로 치환되는 것, 아주 자주 쓰이므로 익숙해져야한다.
      winner = bidder  * 나는 최고 비딩 값을 구하는 것은 되었지만 그 key 값을 찾는 것에 어려웠는데 따로 찾는 것이 아니라 if 에 걸어서 최고값이 될 때는 key 값을 캐치해서 바로 winner에 넣어주는 것이 나에게는 어려웠다. 
  print(f"The winner is {winner} with a bid of ${highest_bid}")

while not bidding_finished:
  name = input("What is your name?: ")
  price = int(input("What is your bid?: $"))
  bids[name] = price
  should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
  if should_continue == "no":
    bidding_finished = True
    find_highest_bidder(bids)
  elif should_continue == "yes":
    clear()