문제1
#제출 답안
def check_inventory(inventory_data, x):
lack_list = []
excess_list = []
for fruit, quantity in inventory_data:
if quantity < x:
lack_list.append(fruit)
elif quantity > x:
excess_list.append(fruit)
print('lack_list: ', list(lack_list))
print('excess_list: ', list(excess_list))
check_inventory(inventory_data, x)
---------------------------------------------
#해설
2차원 리스트 내의 접근 방법을 체크(인덱스, 2차원 자료형)
전달인자를 이용하여 조건문을 설정하는 법을 배워야 함
inventory_date[0][0]
apple
inventory_date[2][1]
50
inven_len = len(inventory_data)
for i in range(inven_len):
print(inventory_data)[i][1]:
30 20 50 ...
---------------------------------------------
range(n) : 0부터 시작하여 n-1까지 만들어주는 내장함수
for i in range(5):
print(i)
for i in [0,1,2,3,4,):
print(i)
0 1 2 3 4, 0, 1, 2, 3, 4
---------------------------------------------
def check)inventory(inventory_data, threshold)
low_stock =[]
high_stock = []
threshold = 30
inven_len = len(inventory_data)
for i in range(inven_len):
product = inventory_data[i][0]
quantity = inventory_data[i][1]
print(product, quantity)
high_stock.append(product)
if quantity >threshold:
print(f'{product)는 과잉입니다.')
low_stock.append(product)
elif quantity < threshold:
print(f'{product}는 부족입니다.')
else:
pass
low,high = check_inventory(inventory_data, 30)
print(low, high)
문제2
#답안
def validate_emails(email_list):
for email in email_list:
if '@' not in email or email.count('@') != 1:
print(f"{email} : 유효하지 않은 이메일 주소입니다.")
continue
else:
if email.startswith('@') or email.endswith('@'):
print(f"{email} : 유효하지 않은 이메일 주소입니다.")
continue
else:
user, domain = email.split('@')
if '.' not in domain or domain.startswith('.') or domain.endswith('.'):
print(f"{email} : 유효하지 않은 이메일 주소입니다.")
continue
else:
print(f"{email} : 유효한 이메일 주소입니다.")
email_list = [
"example@example.com",
"wrongemail@.com",
"anotherexample.com",
"correct@email.co.uk"
]
validate_emails(email_list)
for : email_list 중 email이
if1 : '@'기호가 없거나 1과 같지 않을 경우 (유효하지 않다 출력 / 진행)
if2 : '@'기호가 맨 앞에 있거나 맨 뒤에 있는 경우 (유효하지 않다 출력 / 진행)
else2 : '@'를 기준으로 user와 domain 분리
if3 : '.'이 없거나, '.'이 맨 앞 혹은 맨 뒤에 있는 경우 유효하지 않다 출력
else3 : 유효하다 출력
-----------------------------------------
#해설
문제의 특징
1. 문자열 처리방법을 알아내고 메소드를 활용
- str.split
2. domain에 .이 있는 것을 확인하는 방법
- in
3. 문제 설명에 따르면 .com도 옳은 도메인으로 판단
4. (advanced)re모듈의 정규표현식을 이용해 판단할수도
for email in email_list:
split_list = email.split('@')
print(split_list)
if len(split_list) == 1:
print(f"{email} 유효하지 않은 이메일 입니다.")
continue
if '.' in split_list[1]:
print(f"{email} 유효한 이메일 입니다.")
#if-continue 활용
-----------------------------------------
for email in email_list:
split_list = email.split('@')
print(split_list)
if len(split_list) == 1:
print(f"{email} 유효하지 않은 이메일 입니다.")
elif '.' in split_list[1]:
print(f"{email} 유효한 이메일 입니다.")
#elif 활용
-----------------------------------------
for email in email_list:
split_list = email.split('@')
#print(split_list)
if len(split_list) == 1:
print(f"{email} 유효하지 않은 이메일 입니다.")
else:
if '.' in split_list[1]:
print(f"{email} 유효한 이메일 입니다.")
문제3
#답안
def find_non_completer(participant, completion):
participant_count = {}
for name in participant:
if name in participant_count:
participant_count[name] += 1
else:
participant_count[name] = 1
for name in completion:
participant_count[name] -= 1
for name, count in participant_count.items():
if count > 0:
return name
result = find_non_completer(participant, completion)
print("완주하지 못한 선수:", result)
participant_count : 참가자 명단에서 이름의 등장 횟수를 저장할 딕셔너리를 만든다.
1. for / if : 참가자 명단에서 이름의 등장 횟수를 기록한다.
2. for / if : 완주자 명단에서 이름의 등장 횟수를 뺀다.
3. for / if : 등장 횟수가 0보다 큰 선수의 이름을 return 한다.
--------------------------------------------
#해설
1. 단순한 반복문과 조건문을 통해 체크할 수 있다.
2. 자료를 적절히 선정해야한다. 자료형의 중요성
- set자료형을 통해 쉽게 접근하려고 했다면 lisa의 동명이인의 등장으로 원활하게 구현하기 어려울 수 있다.
-dictionary를 통해 count할 수 있다.
-(Advanced)Counter Module을 통해 구현할 수도
my_dict = {}
for name in participant:
my_dict[name] = my_dict.get(name,0) + 1
print(my_dict)
{'mike': 1, 'lisa': 2, 'tom': 1}
---------------------------------------------
my_dict = {}
for name in participant:
my_dict[name] = my_dict.get(name,0) + 1
for name2 in completion:
ny_dict[name2] = my_dict[name2] - 1
for name3 in my_dict:
if my_dict[name3] == 1:
return name3
----------------------------------------------
from collections import Counter
# Counter(participant)
reult = Counter(participant) - Counter(completion)
result.keys()
문제4
#답안
class Customer:
def join_customer(self, name, email, point):
self.name = name
self.email = email
self.point = point
def add_points(self, amount):
self.point += amount
def reduce_points(self, amount):
if self.point - amount > 0:
self.point -= amount
else:
print("point : 0")
----------------------------------------------
1.클래스 개념과 메소드를 생성하는 방법에 대한 이해
2.init이니셜을 생성하는 것이 기본이나 수준을 고려하여 생략
def join_customer(self, name, email, points):
self.name = name
self.email = email
self.points = points
def add_point(self, amount):
self.points = self.points + amount
print(f'정상적으로 추가되었습니다. 현재 포인트는 {self.points}')
def reduce_point(self, amount):
if amount > self.points:
print(f'포인트가 부족합니다. 현재 포인트는 {self.points}')
else:
self.points = self.points - amount
print(f'정상적으로 차감되었습니다. 현재 포인트는 {self.points}')
my_customer = Customer()
my_customer.join_customer('Alice','alice@example.com',100)
my_customer.add_point(50)
my_customer.reduce_point(20)
my_customer.reduce_point(150)