⌨️ Algorithms/프로그래머스
[Python] 프로그래머스 Lv1_두 개 뽑아서 더하기
monzheld
2022. 12. 30. 21:50
https://school.programmers.co.kr/learn/courses/30/lessons/68644
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
- numbers: 정수 배열
- numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return
제한사항
- numbers의 길이는 2 이상 100 이하
- numbers의 모든 수는 0 이상 100 이하
"""
입출력 예시)
numbers = [2,1,3,4,1] -> [2,3,4,5,6,7]
numbers = [5,0,2,7] -> [2,5,7,9,12]
"""
# numbers = [2,1,3,4,1] -> [2,3,4,5,6,7]
# (-> index: 0 1 2 3 4)
# 2 = 1 + 1 (1이 numbers에 두 개 있음) <- index: 1, 4
# 3 = 2 + 1 <- index: 0, 1 / 0, 4
# 4 = 1 + 3 <- index: 1, 2 / 4, 2
# 5 = 1 + 4 = 2 + 3 <- index: 1, 3 / 4, 3 / 0, 2
# 6 = 2 + 4 <- index: 0, 3
# 7 = 3 + 4 <- index: 2, 3
# => [2,3,4,5,6,7]
## 의사코드 ##
# combinations로 서로 다른 인덱스에 있는 두 개의 수 뽑기
# combinations로 뽑은 두 수 더하기
# 더해서 만들 수 있는 수가 중복될 경우 하나만 배열에 담아 return (-> set()으로 중복 제거)
# 배열을 오름차순으로 정렬
통과한 코드
from itertools import combinations
def solution(numbers):
answer = []
# numbers의 조합 구하기
combi = list(combinations(numbers, 2))
# 조합의 두 수 더하기
for c in combi:
x, y = c[0], c[1]
n = x + y
answer.append(n)
# 중복 제거, 오름차순 정렬
answer = list(set(answer))
answer.sort()
return answer
-> combinations()로 두 개의 수를 뽑아서 더하고, set()으로 중복 제거 후 오름차순 정렬
- combinations() 예시
numbers = [2,1,3,4,1]
from itertools import combinations
list(combinations(numbers, 2))
"""
[(2, 1),
(2, 3),
(2, 4),
(2, 1),
(1, 3),
(1, 4),
(1, 1),
(3, 4),
(3, 1),
(4, 1)]
"""
- combinations vs. permutations
- combinations: 순서 고려 x
- -> AB = BA
- permutations: 순서 고려 o
- -> AB != BA
- combinations: 순서 고려 x
https://monzheld.tistory.com/97
[Python] 프로그래머스 Lv1_폰켓몬
https://school.programmers.co.kr/learn/courses/30/lessons/1845 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는
monzheld.tistory.com