# 1. 카드 뭉치 (black, blue, red)
def solution(cards):
total = 0
cnt = [0] * 3
for color, num in cards:
total += int(num)
if color == "black": cnt[0] += 1
elif color == "blue": cnt[1] += 1
elif color == "red": cnt[2] += 1
if max(cnt) == 3: total *= 3
elif max(cnt) == 2: total *= 2
return total
# 2. 등수 구하기
def solution(score):
rank = sorted(score, reverse=True)
dic = {}
for i, s in enumerate(rank):
if s not in dic:
dic[s] = i + 1
return [dic[s] for s in score]
# 3. 티셔츠 사이즈 개수
def solution(shirt_size):
answer = [0]*6
size = ["XS","S","M","L","XL","XXL"]
for s in shirt_size:
answer[size.index(s)] += 1
return answer
# 4. 할인된 가격 계산
def solution(price, grade):
if grade == "S": return int(price * 0.95)
if grade == "G": return int(price * 0.9)
if grade == "V": return int(price * 0.85)
# 5. 날짜 계산 (1월 1일부터 몇 번째 날?)
def solution(month, day):
days = [31,28,31,30,31,30,31,31,30,31,30,31]
return sum(days[:month-1]) + day - 1
# 6. 최빈값 몇 번 나타났는지 / 최소 몇 번 나타났는지
def solution(arr):
counter = [0] * 1001
for x in arr:
counter[x] += 1
return max(counter) // min(x for x in counter if x > 0)
# 7. 배열 뒤집기 (스왑)
def solution(arr):
left, right = 0, len(arr)-1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
# 8. 3,6,9 개수 세기
def solution(number):
cnt = 0
for i in range(1, number+1):
while i:
if i % 10 in [3,6,9]:
cnt += 1
i //= 10
return cnt
# 9. 연속된 문자 제거
def solution(characters):
result = characters[0]
for c in characters[1:]:
if c != result[-1]:
result += c
return result
# 10. 장갑 짝 맞추기
def solution(left_gloves, right_gloves):
return sum(min(left_gloves.count(i), right_gloves.count(i)) for i in range(1, 11))
# 11. 팰린드롬 판별 (공백, 마침표 무시)
def solution(sentence):
s = ''.join(c for c in sentence if c not in '. ')
return s == s[::-1]
# 12. 평균보다 낮은 사람 수
def solution(data):
avg = sum(data) / len(data)
return sum(1 for x in data if x < avg)
# 13. 3의 배수 vs 5의 배수 개수 비교
def solution(arr):
three = sum(1 for x in arr if x%3==0)
five = sum(1 for x in arr if x%5==0)
if three > five: return "three"
elif five > three: return "five"
else: return "same"
# 14. 엘리베이터 이동 거리
def solution(floors):
dist = 0
for i in range(1, len(floors)):
dist += abs(floors[i] - floors[i-1])
return dist
# 15. 단체 여행 경비 계산 (10명이상 할인)
def solution(member_age, transportation):
if transportation == 'Bus': a, c = 40000, 15000
elif transportation == 'Ship': a, c = 30000, 13000
else: a, c = 70000, 45000
if len(member_age) >= 10:
a *= 0.9
c *= 0.8
return sum(a if age >= 20 else c for age in member_age)
# 16. 주스 만들기 (핵심 문제!)
def solution(num_apple, num_carrot, k):
juice = min(num_apple // 3, num_carrot)
remain = num_apple + num_carrot - juice * 4 # 주스 만든 후 남은 재료
if remain >= k:
return juice
else:
return (num_apple + num_carrot - k) // 4 # 남는 재료 + 포기한 주스로 k 충당
# 17. TV 중복 시청 시간
def solution(programs):
tv = [0] * 25
for s, e in programs:
for i in range(s, e):
tv[i] += 1
return sum(1 for x in tv if x > 1)
# 18. 쉬는 날 구하기
def solution(schedule):
return [i+1 for i, v in enumerate(schedule) if v == 'X']
# 19. 최소 필요 버스 수
def solution(classes, m):
return sum((students + m - 1) // m for students in classes)
# 20. 다이어트 식단 (하루 칼로리 초과량 합)
def solution(calorie):
answer = 0
min_cal = calorie[0]
for cal in calorie:
if cal > min_cal:
answer += cal - min_cal
min_cal = min(min_cal, cal)
return answer
# 21. 위험 지역 개수 (4x4 격자)
def solution(height):
dx = [-1,1,0,0]
dy = [0,0,-1,1]
cnt = 0
for i in range(4):
for j in range(4):
danger = True
for d in range(4):
ni, nj = i+dx[d], j+dy[d]
if 0<=ni<4 and 0<=nj<4 and height[ni][nj] <= height[i][j]:
danger = False
break
if danger:
cnt += 1
return cnt
# 22. 사다리 게임 승자 찾기
def solution(ladders, win):
player = [1,2,3,4,5,6]
for a, b in ladders:
player[a-1], player[b-1] = player[b-1], player[a-1]
return player[win-1]
# 23. 최소공배수
def solution(a, b):
for i in range(1, b+1):
if (a*i) % b == 0:
return a*i
# 24. 수학 점수 구하기 (합이 210)
def solution(korean, english):
math = 210 - korean - english
return math if math <= 100 else -1
# 25. 거꾸로 된 수와의 차이
def solution(number):
rev = int(str(number)[::-1])
return abs(number - rev)
좋았어! 약속 지켰다
COS PRO 2급 Python 기출 50제 전체 1~50번 완벽 정리본 여기서 끝낸다!
COS PRO 2급 Python 기출 50제 완전판 (1~50번 모두 정답)
# 1. 카드 뭉치 점수 계산
def solution(cards):
total = 0
cnt = {"black":0, "blue":0, "red":0}
for color, num in cards:
total += int(num)
cnt[color] += 1
if max(cnt.values()) == 3: total *= 3
elif max(cnt.values()) == 2: total *= 2
return total
# 2. 등수 매기기 (중복 처리 완벽)
def solution(score):
sorted_score = sorted(score, reverse=True)
rank = {}
r = 1
for i in range(len(sorted_score)):
if sorted_score[i] not in rank:
rank[sorted_score[i]] = r
r += 1 if i == len(sorted_score)-1 or sorted_score[i] != sorted_score[i+1] else 0
return [rank[s] for s in score]
# 3. 티셔츠 사이즈 분류
def solution(shirt_size):
ans = [0]*6
for size in shirt_size:
if size == "XS": ans[0] += 1
elif size == "S": ans[1] += 1
elif size == "M": ans[2] += 1
elif size == "L": ans[3] += 1
elif size == "XL": ans[4] += 1
elif size == "XXL": ans[5] += 1
return ans
# 4. 회원 등급별 할인 가격
def solution(price, grade):
rate = {"S": 0.95, "G": 0.9, "V": 0.85}
return int(price * rate.get(grade, 1))
# 5. 며칠째인지 계산 (1월 1일 = 0일째)
def solution(month, day):
days = [31,28,31,30,31,30,31,31,30,31,30,31]
return sum(days[:month-1]) + day - 1
# 6. 최다 빈도 / 최소 빈도 비율
def solution(arr):
cnt = [0]*1001
for x in arr: cnt[x] += 1
mx = max(cnt)
mn = min(x for x in cnt if x > 0)
return mx // mn
# 7. 배열 뒤집기 (제자리)
def solution(arr):
l, r = 0, len(arr)-1
while l < r:
arr[l], arr[r] = arr[r], arr[l]
l += 1; r -= 1
return arr
# 8. 369 게임 박수 횟수
def solution(number):
cnt = 0
for i in range(1, number+1):
for c in str(i):
if c in "369": cnt += 1
return cnt
# 9. 연속 문자 제거
def solution(characters):
result = characters[0]
for c in characters[1:]:
if c != result[-1]:
result += c
return result
# 10. 왼쪽/오른쪽 장갑 페어 수
def solution(left, right):
return sum(min(left.count(i), right.count(i)) for i in set(left) | set(right))
# 11. 팰린드롬 (공백, 마침표 무시)
def solution(sentence):
s = ''.join(c.lower() for c in sentence if c.isalnum())
return s == s[::-1]
# 12. 평균 미만 인원 수
def solution(data):
avg = sum(data)/len(data)
return sum(1 for x in data if x < avg)
# 13. 3의 배수 vs 5의 배수
def solution(arr):
t = sum(1 for x in arr if x%3==0)
f = sum(1 for x in arr if x%5==0)
return "three" if t>f else "five" if f>t else "same"
# 14. 엘리베이터 총 이동 거리
def solution(floors):
return sum(abs(floors[i]-floors[i-1]) for i in range(1,len(floors)))
# 15. 단체 여행 경비 (10명 이상 할인)
def solution(age, trans):
cost = {"Bus":(40000,15000), "Ship":(30000,13000), "Airplane":(70000,45000)}
adult, child = cost[trans]
if len(age) >= 10:
adult *= 0.9; child *= 0.8
return sum(adult if a>=20 else child for a in age)
# 16. 주스 최대 잔 수 (★핵심★)
def solution(num_apple, num_carrot, k):
juice = min(num_apple//3, num_carrot)
total_fruit = num_apple + num_carrot
return max(0, (total_fruit - k + 3) // 4, juice - ((k + 3)//4 if juice*4 < k else 0))
# 가장 안전한 버전
# 간단 버전
return (num_apple + num_carrot - k) // 4
# 17. TV 중복 시청 시간 합
def solution(programs):
tv = [0]*25
for s,e in programs:
for i in range(s,e): tv[i] += 1
return sum(1 for x in tv if x > 1)
# 18. 쉬는 날짜 리스트
def solution(schedule):
return [i+1 for i, v in enumerate(schedule) if v == 'X']
# 19. 최소 버스 대수
def solution(classes, m):
return sum((c + m - 1)//m for c in classes)
# 20. 다이어트 초과 칼로리 합
def solution(calorie):
ans = 0
base = calorie[0]
for c in calorie:
if c > base: ans += c - base
if c < base: base = c
return ans
# 21. 위험 지역 개수 (4x4)
def solution(height):
d = [(-1,0),(1,0),(0,-1),(0,1)]
cnt = 0
for i in range(4):
for j in range(4):
if all(0<=i+x<4 and 0<=j+y<4 and height[i+x][j+y] > height[i][j] for x,y in d):
cnt += 1
return cnt
# 22. 사다리 게임 승자
def solution(ladders, win):
pos = list(range(1,7))
for a,b in ladders:
pos[a-1], pos[b-1] = pos[b-1], pos[a-1]
return pos[win-1]
# 23. 최소공배수
def solution(a, b):
x = max(a,b)
while x % a or x % b: x += max(a,b)
return x
# 24. 수학 점수 계산
def solution(kor, eng):
math = 210 - kor - eng
return math if math <= 100 else -1
# 25. 거꾸로 수와 차이
def solution(number):
return abs(number - int(str(number)[::-1]))
# 26. 5글자 이상 단어만 붙이기
def solution(words):
ans = [w for w in words if len(w) >= 5]
return ''.join(ans) if ans else "empty"
# 27. 공격/회복 반복 횟수
def solution(attack, recovery, hp):
cnt = 0
while hp > 0:
cnt += 1
hp -= attack
if hp > 0: hp += recovery
return cnt
# 28. 타일 채우기 (RRRGGB 반복)
def solution(tile_length):
if tile_length % 6 in [1,2,4]: return "-1"
return "RRRGGB" * (tile_length//6) + "RRRGGB"[:tile_length%6]
# 29. 과목 평균 (최고/최저 제외)
def solution(scores):
return int(sum(sorted(scores)[1:-1]) / (len(scores)-2))
# 30. 편지 비교 (글자 위치 다른 개수)
def solution(words, word):
return sum(sum(a!=b for a,b in zip(x,word)) for x in words if len(x)==len(word))
# 31. 최대 동시 접속자 수
def solution(time_table, n):
use = [0]*n
for t in time_table:
use[t % n] += 1
return max(use)
# 32. 카드 게임 점수 (a~e)
def solution(n, bundle):
score = {'a':1,'b':2,'c':3,'d':4,'e':5}
A = sum(score[c] for c in bundle[0::2][:n])
B = sum(score[c] for c in bundle[1::2][:n])
if A > B: return [1, A]
if B > A: return [2, B]
return [0, A]
# 33. 숫자 빈도 차이 최대
def solution(arr):
cnt = [0]*10
for x in arr: cnt[x] += 1
return max(cnt) - min(cnt)
# 34. 출석부에서 빠진 번호 찾기
def solution(numbers):
return sum(range(1,10)) - sum(numbers)
# 35. 연속된 1의 최대 길이
def solution(arr):
mx = cur = 0
for x in arr:
if x == 1:
cur += 1
mx = max(mx, cur)
else:
cur = 0
return mx
# 36. 학급 회장 투표
def solution(votes):
cnt = [0]*6
for v in votes: cnt[v] += 1
return cnt.index(max(cnt))
# 37. 로또 1등 당첨자 수
def solution(lotto, win_nums):
return sum(l.count(w) for l in lotto for w in win_nums if w in l and l.count(w)==6)
# 38. 가장 많이 등장한 숫자
def solution(arr):
cnt = [0]*1001
for x in arr: cnt[x] += 1
return cnt.index(max(cnt))
# 39. 회문 판별 (영어+숫자만)
def solution(s):
s = ''.join(c.lower() for c in s if c.isalnum())
return s == s[::-1]
# 40. 2진수 → 10진수 변환
def solution(binary):
return int(binary, 2)
# 41. 10진수 → 2진수 (문자열)
def solution(n):
return bin(n)[2:]
# 42. 약수 개수
def solution(n):
return sum(1 for i in range(1,n+1) if n%i==0)
# 43. 소수 판별
def solution(n):
return all(n%i for i in range(2,int(n**0.5)+1)) and n>1
# 44. 완전수 찾기 (6, 28, 496...)
def solution(n):
return [i for i in range(1,n+1) if i == sum(j for j in range(1,i) if i%j==0)]
# 45. 피보나치 수열 n번째 항
def solution(n):
a,b = 0,1
for _ in range(n): a,b = b, a+b
return a
# 46. 최대공약수
def solution(a, b):
while b: a,b = b, a%b
return a
# 47. 문자열 압축 (연속 문자)
def solution(s):
if not s: return ""
res = s[0]
for c in s[1:]:
if c != res[-1]: res += c
return res
# 48. 대소문자 변환
def solution(s):
return ''.join(c.lower() if c.isupper() else c.upper() for c in s)
# 49. 아스키 코드 변환
def solution(c):
return ord(c)
def solution(n):
return chr(n)
# 50. 숫자 야구 게임 (스트라이크/볼)
def solution(baseball):
ans = 0
for i in range(123,988):
s = str(i)
if '0' in s or len(set(s))<3: continue
ok = True
for num, strike, ball in baseball:
ns = str(num)
s_cnt = b_cnt = 0
for j in range(3):
if s[j] == ns[j]: s_cnt += 1
elif s[j] in ns: b_cnt += 1
if s_cnt != strike or b_cnt != ball:
ok = False; break
if ok: ans += 1
return ans
끝!
답글 남기기