BOOTCAMP 4일차

2022. 6. 18. 18:45PYTHON 100 BOOTCAMP

Randomisation

랜덤화, 무작위성

ask python - random module

 

실습1 -  int generator

import random #랜덤모듈 임포트

random-integer = random.randint(1,10)   #1에서 10사이 숫자에서
print(random_integer)

#부동소수점 난수생성기
random_float = random.random() #0과 1 사이 부동소수점 출력
print(random_float)

# random_float * 5 #5는 포함 안됨

Module

복잡한 것을 개발하기 위해 코드가 길어지는 경우, 코드가 너무 방대해 어떤 것이 진행되고 있는지 이해하기 힘듬

코드를 개별 모듈로 나눠 개발

각 모듈은 프로그램에서 서로 다른 기능을 담당

특정 기능을 모아둔 것

Import module

모듈을 사용하기 위해 불러오는 법

 

실습2 - 랜덤 동전 던지기

import random    #random모듈 불러오기

# head = 1, tail = 0
random_side = random.randint(0,1)  #0과 1 사이 의 정수값 랜덤
if random_side == 1:
  print('Heads')
else:
  print('Tails')

Data structure

데이터를 체계화하고 저장하는 방법

List

a = 3, b = "hello" → 하나의 데이터만 저장

서로 관계성있는 데이터 그룹을 저장하거나 데이터의 순서를 지정할 경우 사용

# 대괄호 사용
fruits = [item1, item2]

모든 데이터 형식을 저장가능, 타입이 혼합된 데이터도 저장가능 → 데이터 형식은 상관없다.

Index

색인, 데이터의 위치를 알려줌

인덱스의 시작은 0부터

인덱스가 숫자이고, 데이터 타입이 list일 때 인덱스 구하는 법

  • 리스트 시작 부분에서 이동한 거리나 오프셋
Fruits = [“Cherry”, “Apple”, “Pear”]
#체리의 인덱스 = 0 , 리스트의 시작 부분에서 이동한 거리나 오프셋 = 0

음수 인덱스 = 마지막부분에서 시작, 마지막 부분은 -1 ( -0으로 표시 불가하기에) 

.append()

리스트 추가기능, 마지막 항목으로 추가

.extend()

여러 개의 항목을 리스트 마지막에 추가\

실습3 - Who's paying

계산 전 모든 사람들이 그릇에 명함을 넣고 뽑힌 사람이 모든 계산을 해야한다.

.split()

문자열을 특정 구분 기호에 딸 별도의 구성요소로 나누는 역할

random.choice() 

리스트와 같은 시퀀스에서 무작위 항목을 생성

#My codes
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ") #coma로 구분
# 🚨 Don't change the code above 👆

#Write your code below this line 👇

import random

random_names = random.randint(0,len(names)-1) #입력받은 문자열의 길이 내에서 랜덤, 마지막 값은 포함 안됨?- 항목위치=인덱스가 0부터 시작되기에 
paying_name = names[random_names] # 랜덤으로 나온 값은 정수 = 인덱스라서 값을 출력

print(f"{paying_name} is going to buy the meal today!")
#solution codes
import random

# Split string method
names_string = input("Give me everybody's names, seperated by a comma. ")
names = names_string.split(", ")

#Write your code below this line 👇

#Get the total number of items in list.
num_items = len(names)
#Generate random numbers between 0 and the last index. 
random_choice = random.randint(0, num_items - 1)
#Pick out random person from list of names using the random number.
person_who_will_pay = names[random_choice]

print(person_who_will_pay + " is going to buy the meal today!")

Index out of range error

숫자 하나 차이로 오류 발생 → off - by - one 오류

ex) len( )값을 그대로 넣을 경우 1차이로 에러 발생

Nested list

중첩 리스트 - 리스트 안에 리스트

출력시 [ [ ], [ ] ]

실습4 - Treasure map

#My codes
# 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆

#Write your code below this row 👇

column = int(position[0])-1 #인덱스 값이라 -1 해줌, 인덱스는 0부터 시작
row = int(position[1])-1
map[column][row] = ' X'


#Write your code above this row 👆

# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")
#solution codes
row1 = ["⬜️","️⬜️","️⬜️"]
row2 = ["⬜️","⬜️","️⬜️"]
row3 = ["⬜️️","⬜️️","⬜️️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")

position = input("Where do you want to put the treasure? ")

horizontal = int(position[0])
vertical = int(position[1])

map[vertical - 1][horizontal - 1] = "X"

print(f"{row1}\n{row2}\n{row3}")

오늘의 프로젝트 -  rock paper scissors

바위 = 0, 보 = 1, 가위 = 2

  1. 숫자가 더 크면 win
  2. 숫자가 작으면 lose

예외) 유저 = 0, 컴퓨터 = 2 → 유저 win 

         유저 = 2, 컴퓨터 = 0 컴퓨터 win

#My codes
import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

#Write your code below this line 👇
images = [rock, paper, scissors]

user_choice= int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

print(images[user_choice])

computer_choice = random.randint(0,2)
print("Computer chose: ")
print(images[computer_choice])

# 예외부터 먼저 처리 -> if 문은 위에서부터 해당하지 않아야 elif로 넘어감
if user_choice >=3 or user_choice <0:
  print("You typed an invalid number, you lose!")
  #user = rock, computer = scissors
elif user_choice == 0 and computer_choice ==2: 
  print("You win!")
  #user = scissors, computer = rock
elif user_choice == 2 and computer_choice == 0:
  print("You lose")
elif user_choice < computer_choice:
  print("You lose")
elif user_choice > computer_choice:
  print("You win!")
elif user_choice == computer_choice:
  print("It's a draw")
#solution codes
import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''

game_images = [rock, paper, scissors]

user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
print(game_images[user_choice])

computer_choice = random.randint(0, 2)
print("Computer chose:")
print(game_images[computer_choice])

#예외부터 처리
if user_choice >= 3 or user_choice < 0: 
  print("You typed an invalid number, you lose!") 
elif user_choice == 0 and computer_choice == 2:
  print("You win!")
elif computer_choice == 0 and user_choice == 2:
  print("You lose")
elif computer_choice > user_choice:
  print("You lose")
elif user_choice > computer_choice:
  print("You win!")
elif computer_choice == user_choice:
  print("It's a draw")

'PYTHON 100 BOOTCAMP' 카테고리의 다른 글

BOOTCAMP 5일차  (0) 2022.06.21
BOOTCAMP 3일차  (0) 2022.06.14
BOOTCAMP 2일차  (0) 2022.06.11
BOOTCAMP 1일차  (0) 2022.06.10