(파이썬) 경매 프로그램 만들기

2022. 12. 5. 14:17Trip to Python

유데미를 통해서 100일 부트캠프를 듣고 있는와중 복습을 하라는 선생님의 말씀에 이전에 만들었던 경매 프로그램을 만들어보기로 하였다. 10~20분이면 만들 것이라고 생각했던 내 기대와 달리 나는 문제를 풀지 못했고 큰 충격에 빠졌다. 아무리 진도를 나간들... 만들지 못한다면 무슨 소용인가... 하루에 하나씩은 다시금 복습을 하겠다는 마음을 다잡고 왜 풀지 못했나를 되돌아보았다.

 

1. step by step 

- 차근차근 무엇부터 해나갈지 문제를 쪼개서 생각하고 하나씩 해나갔어야 했는데 그러지 못했다.

 

2. 플로우 차트를 그리지 않았다.

- 1과 일맥상통하지만 밑그림을 그리는 작업이 없이 대략 이렇게 하면 되겠지 하다가 낭패를 보았다. 

 

다시금 코드 짜면서 내가 헤매었던 부분을 체크해본다.


 

 

 

1. 로고 및 필요한 모듈 불러오기

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

- 크게 중요한 내용이 아니라서 패스

 

2. 비드하는 사람의 이름과 비딩 금액을 받고 딕셔너리에 저장

bids = {}

name = input("What is your name?: ")
price = input("What is your bid?: ")
bids[name] = price

- 이름으로 키로 비딩 금액을 값으로 받아 딕셔너리에 저장을 하였다.

 

3. 더 참여하는 사람이 있는지 여부를 확인하고 있으면 반복

bidding_finished = False

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 == "yes"
  	bidding_finished = False
  else:
   	bidding_finished = True
    clear()

-  내가 잘 못했던 부분은 이 부분과 최고 비딩 금액을 확인하는 작업을 분리해서 생각했어야했는데 같이하려고 애쓰다보니까 머리 속만 복잡해지고 꼬여버렸다. 여기까지 하면 bids라는 딕셔너리에 참가하는 인원들의 이름과 각 비딩 금액이 입력된다.

 

4. 딕셔너리에서 최고 비딩 금액과 그 금액을 비딩한 사람을 추려내기

def find_winner(bidding_record):
  highest_bid = 0
  winner = ""
  for bidder in bidding_record:
    bid_amount = bidding_record[bidder]
  	if bid_amount > highest_bid:
      		highest_bid = bid_amount
      		winner = bidder
  print(f"The winner is {winner} with a bid of ${highest_bid}")

- 각 값의 하나씩 접근할 때는 for문을 사용하는 것이 좋다. 여기서 중요한 것은 새로운 변수를 만들어서 그 변수에 가장 높은 값을 저장한다는 프로세스를 떠올리는 것. 해당 조건을 만족할 때 새로운 변수에 기존 값들을 저장한다. for와 if의 조합을 잘 기억해야할 것 같다. 그리고 for 문이 끝났을 때 최종 결과 출력.

 

5. 더 이상 비딩하는 사람이 없을 때 최종 결과 출력

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

bids = {}
bidding_finished = False

def find_winner(bidding_record):
  highest_bid = 0
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:
    bid_amount = bidding_record[bidder]
    if bid_amount > highest_bid: 
      highest_bid = bid_amount
      winner = bidder
  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_winner(bids)
  elif should_continue == "yes":
    clear()

- 함수 인자로는 bids 딕셔너리를 넣어서 이전에 저장한 참여자들 목록을 함수에 넣고 최고 금액 비더를 판별.