📖저자님의 책 소개 영상: https://www.youtube.com/watch?v=Q13Uj_5bH9M
💪 내 목표: 차근차근 클린 코딩 근육 만들기, 내 코드가 깔끔했으면 좋겠다.
📚 이 책의 목표: 코딩 테스트 합격이라는 목표에 충실하되,
공부한 사람이 다른 사람에게 잘 설명할 수 있는 수준으로 만들어보자!여긴.. 어디...? 나는 누구...?
def total_price(quantity, price):
total = quantity * price
if total > 100:
return total * 0.9
return total
print(total_price(4,50))
def calculate_averate(numbers):
if numbers is None:
return None
if not isinstance(numbers,list):
return None
if len(numbers) == 0:
return None
total = sum(numbers)
average = total / len(numbers)
return average
몸풀기 문제 중, sorted(), sort()의 성능 차이가 궁금해져서 검색.
(나는 습관적으로 sorted()를 주로 사용한다.)
https://wyatti.tistory.com/entry/Python-sort-sorted-%EC%B0%A8%EC%9D%B4%EC%A0%90
https://school.programmers.co.kr/learn/courses/30/lessons/68644
def solution(numbers):
solution = []
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
solution.append(numbers[i]+numbers[j])
answer = sorted(set(solution))
return answer
from itertools import combinations
def solution(numbers):
return sorted(set(sum(i) for i in list(combinations(numbers, 2))))
https://school.programmers.co.kr/learn/courses/30/lessons/42840
def solution(answers):
pattern1 = [1,2,3,4,5]
pattern2 = [2,1,2,3,2,4,2,5]
pattern3 = [3,3,1,1,2,2,4,4,5,5]
scores = [0, 0, 0]
result = []
for i, answer in enumerate(answers):
if answer == pattern1[i%len(pattern1)]:
scores[0] += 1
if answer == pattern2[i%len(pattern2)]:
scores[1] += 1
if answer == pattern3[i%len(pattern3)]:
scores[2] += 1
for i, score in enumerate(scores):
if score == max(scores):
result.append(i+1)
return result
# 책 풀이
def solution(answers):
patterns = [
[1,2,3,4,5],
[2,1,2,3,2,4,2,5],
[3,3,1,1,2,2,4,4,5,5]
]
scores = [0] * 3
for i, answer in enumerate(answers):
for j, pattern in enumerate(patterns):
if answer == pattern[i % len(pattern)]:
scores[j] += 1
max_score = max(scores)
highest_scores = []
for i, score in enumerate(scores):
if score == max_score:
highest_scores.append(i+1)
return highest_scores
◾ 코테에서 자주 만나는 enumerate
(참고: https://www.daleseo.com/python-enumerate/ 위 사이트 내용을 토대로 정리함)
for i, letter in enumerate(['A','B','C']):
print(i, letter)
matrix = [['A','B','C'],['D','E','F'],['G','H','I']]
for r, row in enumerate(matrix):
for c, letter in enumerate(row):
print(r,c,letter)
https://school.programmers.co.kr/learn/courses/30/lessons/12949
def solution(arr1, arr2):
# 행과 열의 수
r1, c1 = len(arr1), len(arr1[0])
r2, c2 = len(arr2), len(arr2[0]) # for문에 len(~)로 넣어도 됨
ret = [[0] * c2 for _ in range(r1) ] # 2차원 리스트 초기화
# ex) (3X2행렬) * (2X2행렬) = 3(r1)X2(c2)행렬
for i in range(r1):
for j in range(c2):
for k in range(c1):
ret[i][j] += arr1[i][k] * arr2[k][j] # 이게 되네..? ㅋㅋㅋㅋㅋ
return ret
https://school.programmers.co.kr/learn/courses/30/lessons/42889
def solution(N, stages):
challenger = [0] * (N+2)
for stage in stages:
challenger[stage] += 1
fails = {}
total = len(stages)
# 실패율 계산
for i in range(1, N+1):
if challenger[i] == 0:
fails[i] = 0
else:
fails[i] = challenger[i] / total
total -= challenger[i]
result = sorted(fails,key = lambda x: fails[x], reverse=True)
return result
https://school.programmers.co.kr/learn/courses/30/lessons/49994
🤔 중복은 어떻게? -> set
좌표평면 경계를 넘어가는 명령어는 무시!
기능별 구현: 일단 하나의 함수로 전체 동작을 구현하고 이후에 함수로 나누는 연습
def is_valid_move(nx, ny):
return 0 <= nx < 11 and 0 <= ny < 11
def update_location(x,y,dir): # 좌표
if dir == 'U':
nx, ny = x, y + 1
elif dir == 'D':
nx, ny = x, y - 1
elif dir == 'R':
nx, ny = x + 1, y
elif dir == 'L':
nx, ny = x - 1 , y
return nx, ny
def solution(dirs):
x, y = 5, 5
ans = set()
for dir in dirs:
nx, ny = update_location(x, y, dir)
if not is_valid_move(nx,ny):
continue
ans.add((x,y,nx,ny)) #<- 요기가 이해가 안 됨
ans.add((nx,ny,x,y))
x,y = nx,ny
return len(ans)/2