라이브러리(numpy, matplotlib, pandas)의 기초를 배웠다. 파이썬 따라가기도 힘든데 라이브러리까지 하려니 머리가 터질 것 같다. 오늘 교육량이 엄청나다. 지난주 목&금 합친 것의 2배 이상 되는 느낌... 주말에 객체와 클래스를 어느 정도 복습해 두어서 금방 푼 문제도 있다. 아직 다른 학생들에 비해 한참 부족하지만 그래도 이제 클래스 코드는 이해하면서 리딩할 수 있다. 진짜 신기함. 그리고 벨로그 코드블럭에 색상 넣는 법을 알았다!
numpy 관련 함수를 익히는 게 급선무인 것 같다. 특히 슬라이싱에선 뭐가 뭔지 하나도 모르겠다.
학습시간 09:00~01:00(당일16H/누적54H)
# 리스트 컴프리헨션 예시
total = sum(len(branch.reservations) for branch in branches)
total = sum(len(emp.salary for emp in cls.employees)
# enumerate 함수 사용 예시
fruits = ['사과', '바나나', '체리']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 올바른 사용 예시
d = {"a": "b", "c": "d"}
print(d["a"]) # b
# 틀린 사용 예시 (❌ SyntaxError 발생❌)
d = {"a": "b": "c"}
np.array(1, 2, 3) # 튜플을 넘겨주면 numpy 배열로 변환
np.zeros((2, 3)) # 2 * 3 크기의 zero 값 배열 생성
np.arange(1, 10, 2) # 1이상 10미만 2씩 더하며 배열 생성
array.size # 배열 총 요소 개수 반환
array.dtype # 배열 데이터 타입 확인
array.shape # 배열 차원(행, 열) 정보 반환
array.mean # 배열 요소 평균 반환
array.sum # 배열 요소 합 반환
array.min # 배열 최소값 반환
array.max # 배열 최대값 반환
array.[1:3] # 1이상 3미만 인덱스 슬라이싱
array.[1, 3] # 1번 행 & 3번 열 요소 값 반환
array.[:, -1] # 모든 행 마지막 열 요소 값 반환
array.[0:2, 1] # 0번 이상 & 2번 미만, 1번 열 값 반환
array.[[0, 2]] # 0번, 2번 행 값 반환
array.[] *-+/ 2 # (숫자 연산 가능)
mask = array > 7000 # 불린값 True or False 나옴
array[mask] = True # 이렇게 하면 True인 값만 나옴
array.mean() == sum([1, 2, 3]) / 3 # 서로 동일한 연산
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8)) # 그래프 사이즈 설정
plt.rc('font', family='Malgun Gothic') # 한글 폰트 설정 (맑은 고딕)
plt.rc('axes', unicode_minus=False) # 마이너스 기호 깨짐 방지
plt.scatter(x_array, y_array, color='red', marker='s')
plt.title("Apple Stock Prices Over Time") # 타이틀 설정
plt.xlabel("Year") # X축 이름
plt.ylabel("Price (USD)") # Y축 이름
plt.show() # 그래프 출력
x_array = np.array([2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020])
y_array = np.array([14.46, 19.01, 20.04, 27.59, 26.32, 28.96, 42.31, 39.44, 73.41, 132.69])
import pandas as pd
df = pd.DataFrame({
‘series_1’: [‘a’, ‘b’, ‘c’],
‘series_2’: [1, 2, 3],
‘series_3’: [1000, 2000, 3000]
})
df[‘series’] # 시리즈 열 출력
df[‘series’].mean # 평균
df[‘series’].sum # 합
df[‘series’].min # 최소값
df[‘series’].max # 최대값
df[‘series_1’] * df[‘series_2’] # 시리즈 간 곱
from datetime import datetime
class TimeTracker():
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
self.start_time = datetime.now()
print("타이머 시작, 현재시간:", self.start_time.strftime("%H시 %M분 %S초"))
def stop(self):
self.end_time = datetime.now()
print("타이머 종료, 현재시간:",self.end_time.strftime("%H시 %M분 %S초"))
def get_elapsed_time(self):
elapsed_time = (self.end_time - self.start_time).total_seconds() / 60
return elapsed_time
study_session = TimeTracker()
while True:
command = input('"시작" 혹은 "종료"를 입력하세요.')
if command == "시작":
study_session.start()
elif command == "종료":
study_session.stop()
elapsed = study_session.get_elapsed_time()
if elapsed is not None:
print(f"공부한 시간: {elapsed:.1f}분")
break
else:
print("잘못된 명령어 입니다.")
class Contact:
def __init__(self, name, number, email):
self.name = name
self.number = number
self.email = email
def __str__(self):
return (
f"이름: {self.name}\n"
f"전화번호: {self.number}\n"
f"이메일: {self.email}\n"
)
friend = Contact("Jane Doe", "010-1234-5678", "jane@example.com")
print(friend)
class VoteSystem:
def __init__(self):
self.candidate_list = {}
# 1. 후보자 등록(이름을 입력 받아 목록에 추가)
def add_candidate(self, name):
if name not in self.candidate_list:
self.candidate_list[name] = 0 # 딕셔러니에 [이름: 투표수] 생성
print(f"{name} 후보가 성공적으로 등록되었습니다.")
# 2. 후보자 투표(존재하는 이름에 1회 투표)
def vote(self, name):
if name in self.candidate_list:
self.candidate_list[name] += 1
print(f"{name}에게 투표하였습니다.")
# 3. 투표 결과 출력
def get_results(self):
print("투표 결과")
for name, votes in self.candidate_list.items():
print(f"{name}: {votes} votes")
# 사용 예시
voting_system = VoteSystem()
voting_system.add_candidate("Alice")
voting_system.add_candidate("Bob")
voting_system.add_candidate("Charlie")
voting_system.vote("Alice")
voting_system.vote("Alice")
voting_system.vote("Bob")
voting_system.get_results()
"""
# 예상 출력
Alice 후보가 성공적으로 등록되었습니다.
Bob 후보가 성공적으로 등록되었습니다.
Charlie 후보가 성공적으로 등록되었습니다.
Alice에게 투표하였습니다.
Alice에게 투표하였습니다.
Bob에게 투표하였습니다.
투표 결과:
Alice: 2 votes
Bob: 1 vote
Charlie: 0 votes
"""
class BankAccount:
# 1. 계좌번호, 소유자 이름, 잔액 설정
def __init__(self, account_number, account_holder, balance):
self.account_number = account_number
self.account_holder = account_holder
self.balance = int(balance)
print(f"{self.account_holder}님의 계좌 {self.account_number}가 개설되었습니다. 초기 잔액: {self.balance}원")
# 2. 입금 설정
def deposit(self, deposit):
if deposit > 0:
self.balance += deposit
print(f"{deposit}원이 입금되었습니다. 현재 잔액: {self.balance}원")
else:
print("금액 금액이 없습니다.")
# 3. 출금 설정
def withdraw(self, withdraw):
if withdraw > 0:
self.balance -= withdraw
print(f"{withdraw}원이 출금되었습니다. 현재 잔액: {self.balance}원")
else:
print("출금 금액이 없습니다.")
# 4. 현재 잔액 설정
def get_balance(self):
return self.balance
# 사용 예시
my_account = BankAccount("123-456-789", "김철수", 100000)
my_account.deposit(50000)
my_account.withdraw(20000)
print(f"현재 잔액: {my_account.get_balance()}원")
"""
# 예상 출력
김철수님의 계좌 123-456-789가 개설되었습니다. 초기 잔액: 100000원
50000원이 입금되었습니다. 현재 잔액: 150000원
20000원이 출금되었습니다. 현재 잔액: 130000원
현재 잔액: 130000원
"""
class ReservationSystem:
reservation_list_all = []
# 1. 지점명 설정
def __init__(self, location):
self.location = location
self.reservation_list_location = []
# 2. 예약 추가
def add_reservation(self, customer_name, visit_date, pax):
reservation = [customer_name, visit_date, pax]
self.reservation_list_location.append(reservation)
ReservationSystem.reservation_list_all.append(reservation)
# 3. 예약 삭제
def del_reservation(self):
pass
# 4. 예약 조회
def list_reservations(self):
print(f"{self.location} 예약 목록:")
for search in self.reservation_list_location:
print(f'- {search[0]}, {search[1]}, {search[2]}명')
# 5. 예약 집계
@classmethod
def sum_reservations(cls, branches):
total = sum(len(branch.reservation_list_location) for branch in branches)
return total
# 사용 예시
restaurant1 = ReservationSystem("강남점")
restaurant2 = ReservationSystem("홍대점")
restaurant1.add_reservation("홍길동", "2024-05-20", 4)
restaurant2.add_reservation("김철수", "2024-05-21", 2)
restaurant1.list_reservations()
restaurant2.list_reservations()
total_reservations = ReservationSystem.sum_reservations([restaurant1, restaurant2])
print(f"전체 레스토랑 예약 수: {total_reservations}")
"""
# 예상 출력
강남점 예약 목록:
- 홍길동, 2024-05-20, 4명
홍대점 예약 목록:
- 김철수, 2024-05-21, 2명
전체 레스토랑 예약 수: 2
"""
### 문제를 위한 파일 생성코드입니다. 문제를 풀기 전 이 코드를 반드시 실행해주세요.
import csv
# (시뮬레이션을 위한) 예시 파일 작성코드
def write_tasks_to_csv(filename, tasks):
with open(filename, 'w', newline='') as csvfile:
fieldnames = ['할일', '소요시간']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for task, time in tasks:
writer.writerow({'할일': task, '소요시간': time})
# 할 일과 소요 시간 데이터
tasks = [
('공부하기', 120),
('운동하기', 60),
('가계부정리', 30),
('영화보기', 150)
]
# CSV 파일로 저장
write_tasks_to_csv('tasks.csv', tasks)
# 문제 시작!!!
import csv
# 문제
def load_tasks(filename):
pass
def suggest_tasks(tasks, remaining_time):
pass
def main():
pass
# 프로그램 실행
if __name__ == "__main__":
main()
"""
# 출력 예시
선택된 할 일 목록:
1. 가계부정리 - 예상 소요 시간: 30분
2. 운동하기 - 예상 소요 시간: 60분
3. 공부하기 - 예상 소요 시간: 120분
"""
# 문제
def is_prime(num):
pass
def sum_of_primes(n):
pass
def main():
pass
# 프로그램 실행
if __name__ == "__main__":
main()
"""
# 출력 예시
10 이하 소수의 합은 17입니다.
"""