본문 바로가기
Python/개념

Day 6. 과제_가위바위보

by 사라리24 2024. 3. 18.
SMALL

과제1

가위, 바위, 보 게임 만들기

가위, 바위, 보 중 하나를 입력하세요: 가위
컴퓨터: 바위 / 유저: 가위 -> 결과: 컴퓨터 승
랜덤한 값을 뽑는 프로그램

 

# 내가 짜본 코드

 
 
  import random

    user = input('가위, 바위, 보 중 하나를 입력하세요: ')

  def choice():
    if user == '가위':
      user == 1
    elif : '바위':
      user == 2
    elif : '보' :
      user == 3
    else : '잘못입력하셨습니다 다시 입력해주세요.'

  computer = int(random.randint(1,4))

  def play():
    if computer = user :
        return '무승부입니다.'

    elif : (user == 1 and computer == 3) or (user == 2 and computer == 1) or  (user == 3 and computer == 2):
       return "사용자 승!"
   else:
      return "컴퓨터 승!"

  choice()
  print(f"사용자: {user}")
  print(f"컴퓨터: {computer}")
  play()


 
실행결과가 뜨지 않음 

ㄴ결과가 뜨지 않은 이유를 살펴보고 수정보완해야 할 것 같습니다.

ㄴ실행된 예시와 비교하며 공부해보도록 하겠습니다.

 

(1)  가위바위보가 실행된 예시

  
  import random

  def get_user_choice():
      while True:
          user_choice = input("가위, 바위, 보 중 하나를 선택하세요: ").lower()
          if user_choice in ["가위", "바위", "보"]:
              return user_choice
          else:
              print("잘못된 입력입니다. 다시 시도하세요.")

  def get_computer_choice():
      choices = ["가위", "바위", "보"]
      return random.choice(choices)

  def determine_winner(user_choice, computer_choice):
      if user_choice == computer_choice:
          return "무승부"
      elif (user_choice == "가위" and computer_choice == "보") or \
           (user_choice == "바위" and computer_choice == "가위") or \
           (user_choice == "보" and computer_choice == "바위"):
          return "사용자 승!"
      else:
          return "컴퓨터 승!"

  def play_game():
      user_choice = get_user_choice()
      computer_choice = get_computer_choice()
      print(f"사용자: {user_choice}")
      print(f"컴퓨터: {computer_choice}")
      print(determine_winner(user_choice, computer_choice))
 

  if __name__ == "__main__":
      play_game()
 
가위, 바위, 보 중 하나를 선택하세요: 가위
사용자: 가위
컴퓨터: 보
사용자 승! 

 

(2)  가위바위보가 실행된 예시

 
  import random

  def get_user_choice():
      while True:
          user_choice = input("가위, 바위, 보 중 하나를 선택하세요: ").lower()
          if user_choice in ["가위", "바위", "보"]:
              return user_choice
          else:
              print("잘못된 입력입니다. 다시 시도하세요.")
 
  def get_computer_choice():
      random_number = int(random.random() * 10)
      if random_number < 4:
          return "가위"
      elif random_number < 7:
          return "바위"
      else:
          return "보"

  def determine_winner(user_choice, computer_choice):
      if user_choice == computer_choice:
          return "무승부"
      elif (user_choice == "가위" and computer_choice == "보") or \
           (user_choice == "바위" and computer_choice == "가위") or \
           (user_choice == "보" and computer_choice == "바위"):
          return "사용자 승!"
      else:
          return "컴퓨터 승!"

  def play_game():
      user_choice = get_user_choice()
      computer_choice = get_computer_choice()
      print(f"사용자: {user_choice}")
      print(f"컴퓨터: {computer_choice}")
      print(determine_winner(user_choice, computer_choice))

  if __name__ == "__main__":
      play_game()
 
 
가위, 바위, 보 중 하나를 선택하세요: 가위
사용자: 가위
컴퓨터: 보
사용자 승!

 

과제2


로또 예측 프로그램을 작성해보자

* 1~45까지의 임의의 수 6개를 출력
* 중복된 숫자가 없어야 함
* 오름차순으로 출력

 

# 내가 짠 코드

 
  num = []
  def ran(li):   # 랜덤 6개
      for i in range(6):
          li.append(random.randint(1, 45))
          li.sort()  #오름차순
      return li
  num = ran(num)

  # 중복제거
  def overlap(li):
      if len(set(li)) ==  6:
          return li
      else:
          li = []
          li = ran(li)
          return li
  num = overlap(num)
  print(f'예상 번호는: {num}')
 
예상 번호는: [5, 7, 14, 21, 33, 33]

ㄴ 중복제거하기 위해 비우고 다시 채우는 함수 overlap에서 다시 중복된 숫자가 뜰 수도 있다는 문제점이 있습니다.

ㄴ 이 부분을 해결하기 위해서 다른 실행된 코드를 비교하여 공부해보겠습니다.

 

(1) 실행된 예시

  
  import random

  def generate_unique_number():
      while True:
          # 랜덤한 6자리 숫자 생성
          number = ''.join(random.sample('0123456789', 6))
          # 중복되지 않는지 확인
          if len(set(number)) == 6:
              return number

  # 중복되지 않는 6자리 숫자 출력
  print(generate_unique_number())
 
678349

 

ㄴ> 사용한 함수

* random.sample(range(p, q), r)
p부터 q-1까지 r 개의 겹치지 않는 랜덤 한 값을 출력합니다.

 

 

(2) 실행된 예시

 
  import random

  def generate_lottery_numbers():
      lottery_numbers = []
      while len(lottery_numbers) < 6:
          number = random.randint(1, 45)
          if number not in lottery_numbers:
              lottery_numbers.append(number)
      lottery_numbers.sort()
      return lottery_numbers

  if __name__ == "__main__":
      lottery_numbers = generate_lottery_numbers()
      print("로또 번호:", lottery_numbers)
 
 
로또 번호: [5, 15, 24, 34, 38, 42]

 

'Python > 개념' 카테고리의 다른 글

Day 8-1. 파이썬 모듈  (0) 2024.03.20
Day 7. 과제_주민번호 유효성 검사  (0) 2024.03.20
Day 7-3. 파이썬의 예외처리  (0) 2024.03.18
Day 7-2. 파이썬 스페셜(매직) 메소드  (0) 2024.03.18
Day 7-1. 파이썬 상속  (0) 2024.03.18