반응형
스파르타 코딩클럽 내일배움캠프 AI 웹개발자양성과정 3회차
2022.09.07. 8일차 - TIL
1. 파이썬 특강
- randrange(n, m) : n 이상 m 미만의 난수 생성
- randint(n, m) : n 이상 m 이하의 난수 생성
- datetime.now() : 현재 날짜 및 시간 출력
from datetime imort datetime, timedelta
'''
%y : 두 자리 연도 / 20, 21, 22
%Y : 네 자리 연도 / 2020, 2021, 2022
%m : 두 자리 월 / 01, 02 ... 11 ,12
%d : 두 자리 일 / 01, 02 ... 30, 31
%I : 12시간제 시간 / 01, 02 ... 12
%H : 24시간제의 시간 / 00, 01 ... 23
%M : 두 자리 분 / 00, 01 ... 58, 59
%S : 두 자리 초 / 00, 01 ... 58, 59
'''
# string을 datetime 날짜로 변경
# strptime : 날짜와 시간 형식의 문자열을 datetime으로 변환
string_datetime = "22/12/25 13:20"
datetime_ = datetime.strptime(string_datetime, "%y/%m%d %H:%M")
print(datetime_) # 2022-12-25 13:20:00
# datetime 날짜를 string으로 변환하기
# strftime : 날짜와 시간을 문자열로 출력
now = datetime.now()
string_datetime = datetime.strftime(now, "%y/%m/%d %H:%M:%S")
print(string_datetime) # 22/09/04 04:04
# datetime 날짜를 string으로 변환하기
now = datetime.now()
string_datetime = datetime.strftime(now, "%y/%m/%d %H:%M:%S")
print(string_datetime) # 22/09/04 04:04
- 로또 번호 뽑기 코드
import random
# count 횟수만큼 일련의 로또 번호 생성 함수
def get_lotto_number(count):
result = []
if count < 1:
print("1 이상의 값을 입력해주세요")
# 인덱스를 사용하지 않을 경우 _으로 처리
for _ in range(count): 총 count만큼 반복
lotto = set() # 로또 번호를 담을 집합 준비
while len(lotto) < 8: # 총 8개의 숫자 뽑기
lotto.add(random.randint(1, 45)) # 1~45 중 랜덤한 숫자를 뽑아 집합에 추가
result.append(lotto) # 생성한 로또 번호 리스트에 추가
return result # 생성한 로또 번호 리스트 보여주기
- 과제(숫자 야구)
import random
import sys
import time
# 해당 자릿수 만큼 랜덤한 수 생성
def get_number(n):
result = []
if n < 1:
print("1 이상의 값을 입력해주세요")
elif n > 10:
print("10 이하의 값을 입력해주세요")
while len(result) < n:
a = random.randint(1, 9)
if a not in result:
result.append(a)
return result
# 스트라이크 개수 카운팅 함수
def check_strike(command_list, answer_list):
count = 0
for i in range(len(answer_list)):
if command_list[i] == answer_list[i]:
count += 1
return count
# 볼 개수 카운팅 함수(하지만 스트라이크도 함께 카운팅하기에 후에 스트라이크 개수 빼주기)
def check_ball(command_list, answer_list):
count = 0
for num in command_list:
if num in answer_list:
count += 1
return count
# 게임을 몇 자리 숫자로 할 것인지
n = int(input())
count = 0
# 정답 생성
answer = get_number(n)
start_time = time.time() # 현재 시간
# 명령어 or 숫자 입력
print(answer)
command = input("숫자를 입력하세요 : ")
while True:
if command == "exit": # 명령어가 exit인지 확인 후 시스템 종료
sys.exit(0)
count += 1
command = list(map(int, command.split())) # 숫자화 후 재저장
strike = check_strike(command, answer)
ball = check_ball(command, answer) - strike
if strike == len(answer): # 숫자와 위치가 전부 맞을 때 스트라이크!!
end_time = time.time()
print("스트라이크!!!!")
print(f'{count}번의 숫자를 입력했습니다')
print(f"코드 실행 시간 : {end_time - start_time:.5f}")
break
elif strike == 0 and ball == 0:
print("아웃!!!")
else:
print(f'{strike}S {ball}B!!')
command = input("다시 숫자를 입력하세요 : ")
2. 백준
- 제일 힘들었던 문제 투척
# 자연수 집합
natural_num = set(range(1, 10001))
# 생산자가 있는 숫자를 넣을 집합
generated_num = set()
for i in range(1, 10001): # i = 850
for j in str(i): # j = "8", "5", "0"
i += int(j) # 850 + 8 + 5 + 0, i=863
generated_num.add(i) # 생산자가 있는 숫자들
# 자연수 집합에서 생산자가 있는 숫자들의 집합을 제외한 집합
self_num = sorted(natural_num - generated_num)
for i in self_num:
print(i)
Tip)
- 어떤 수의 각 자릿수를 이용하는 문제는 정수형보다 문자열로 리스트에 넣어서 관리하는게 편함
- 특히 파이썬은 문자열을 간단히 for문을 이용해 각 문자에 접근이 가능함
- 차집합을 이용한 동일 요소 제거
* sort와 sorted의 차이
3. 후기
오늘 과제로 받은 파이썬 문제가 꽤 힘들었다. 일단 알고리즘을 구조화 시키는 부분에서 다소 어려움을 느꼈다. 무작정 코딩보다 먼저 알고리즘을 구체화 시키는 과정을 연습해보자. 이런 부분이 부족하다고 느낀게 백준 알고리즘 문제를 풀 때도 문제풀이를 굉장히 복잡하게 생각했는데 다른 이들의 풀이를 보면 간단했기 때문이다.(구조화, 단순화 기억하기!) 그리고 구글링에 너무 죄책감을 느끼지 말고, 오히려 더 자세하게 분석해서 다시 코드를 작성하는 과정을 연습해야겠다.
반응형
'개발일지 > AI 캠프' 카테고리의 다른 글
내일배움캠프 AI - 2주차 WIL (0) | 2022.09.13 |
---|---|
내일배움캠프 AI - 9일차 TIL, 2022.09.08 (0) | 2022.09.13 |
내일배움캠프 AI - 7일차 TIL, 2022.09.06 (0) | 2022.09.06 |
내일배움캠프 AI - 6일차 TIL, 2022.09.05 (0) | 2022.09.06 |
내일배움캠프 AI - 1주차 WIL (1) | 2022.09.04 |