[코드트리 챌린지] 객체_연습 문제 & 테스트

HKTUOHA·2023년 9월 27일
0

코드트리

목록 보기
5/15
post-thumbnail

⭐실력진단 결과



구조체(클래스)를 선언하고 사용하는 방법에 대해 배우게 됩니다.

🟢폭탄 해제

📌문제


📌나의 코드

class Bomb:
    def __init__(self, code, color, second):
        self.code = code
        self.color = color
        self.second = second

i_code, i_color, i_second = tuple(input().split())
ans = Bomb(i_code, i_color, i_second)

print(f'code : {ans.code}')
print(f'color : {ans.color}')
print(f'second : {ans.second}')



🟢상품 코드

📌문제


📌나의 코드

class Product:
    def __init__(self, name="", code=0):
        self.name = name
        self.code = code

i_name, i_code = tuple(input().split())
i_code = int(i_code)

p1 = Product()
p1.name = "codetree"
p1.code = 50

p2 = Product(i_name, i_code)

print(f'product {p1.code} is {p1.name}')
print(f'product {p2.code} is {p2.name}')



🟢사는 지역

📌문제


📌나의 코드

class Address:
    def __init__(self, name="", street="", region=""):
        self.name = name
        self.street = street
        self.region = region

# 자료 수
n = int(input())

# 이름 순으로 자료 리스트 생성
dictionary = [tuple(input().split()) for _ in range(n)]
dictionary.sort()

# 이름이 가장 느린 사람 자료로 객체 생성
a, b, c = dictionary[-1]
last = Address(a, b, c)

print(f'name {last.name}')
print(f'addr {last.street}')
print(f'city {last.region}')

✏️다른 풀이

  • class로 객체 리스트를 만들고 index를 이용할 수 있다.
...
people = [Address(name, address, region) for name, address, region in dictionary]
...
target_idx = 0
for i, person in enumerate(people):
    if person.name > people[target_idx].name:
        target_idx = i
...




✔️테스트

🟢비오는 날

📌문제


📌나의 코드

class Data:
    def __init__(self, date, day, weather):
        self.date = date
        self.day = day
        self.weather = weather

# 데이터 수
n = int(input())
predict = [tuple(input().split()) for _ in range(n)]
rains = [Data(date, day, weather) for date, day, weather in predict if weather == "Rain"]

target_idx = 0
for i, rain in enumerate(rains):
    if rain.date < rains[target_idx].date:
        target_idx = i

print(rains[target_idx].date, rains[target_idx].day, rains[target_idx].weather)

✏️다른 풀이

  • class를 초기화한 변수 사용 가능
ans = Date("9999-99-99", "", "")
profile
공부 기록

0개의 댓글