[문제]
[내 코드]
- 버전1 (39184KB, 92ms)
import random
heights = [int(input()) for _ in range(9)]
while True:
sampled = random.sample(heights, 7)
if sum(sampled)==100:
for s in sorted(sampled):
print(s)
break
- 버전2 (30840KB, 68ms)
def foo(heights):
diff = sum(heights) - 100
for i in range(len(heights)):
first = heights[i]
for j in heights[i+1:]:
second = j
if diff == (first+second):
heights.remove(first)
heights.remove(second)
return sorted(heights)
for f in foo([int(input()) for _ in range(9)]):
print(f)
- 하나는 random으로 7개 뽑아서 더했고, 하나는 두 개로 된 쌍을 찾아가며 구했다
- 속도는 후자가 훨씬 빨랐다
- nested for loop을 끝내고 싶어서 함수의 return으로 처리했다 -> 잘한 것 같다
[다른 코드]
for i in range(8):
for j in range(i+1, 9):
if sum(s) - (s[i]+s[j]) == 100:
s1 = s[i]
s2 = s[j]
s.remove(s1)
s.remove(s2)
for i in s:
print(i)
- 이렇게 풀면 합이 100이 되는 가능성 중에 가장 마지막 가능성까지 샅샅이 찾아보게 되지 않나.. for문을 멈추지 않으니까?
- 가독성 면에서는 배울 점이 많다 (접근법은 근본적으로 같음에도 가독성 차이가..)
'컴퓨터 > 코딩테스트' 카테고리의 다른 글
[백준/튼튼한기본기] 2693번: N번째 큰 수 (0) | 2022.09.12 |
---|---|
[백준/튼튼한기본기] 2609번: 최대공약수와 최대공배수 (0) | 2022.09.12 |
[백준/튼튼한기본기] 10870번: 피보나치수 5 (0) | 2022.09.11 |
[백준/튼튼한기본기] 2460번: 지능형 기차 2 (1) | 2022.09.11 |
[백준/튼튼한기본기] 10818번: 최소, 최대 (0) | 2022.09.10 |