파이썬의 리스트 remove는 여러 번 하는 경우 잘 작동하지 않는 것 같다.
ans = [h for h in heights if h not in [ih, jh]]
이런 list comprehension을 사용하는 게 좋은 거 같다.
itertools에 대해 더 알아보자.
https://docs.python.org/ko/3/library/itertools.html
| 이터레이터 | 인자 | 결과 |
|---|---|---|
product() |
p, q, … [repeat=1] | 데카르트 곱(cartesian product), 중첩된 for 루프와 동등합니다 |
permutations() |
p[, r] | r-길이 튜플들, 모든 가능한 순서, 반복되는 요소 없음 |
combinations() |
p, r | r-길이 튜플들, 정렬된 순서, 반복되는 요소 없음 |
combinations_with_replacement() |
p, r | r-길이 튜플들, 정렬된 순서, 반복되는 요소 있음 |
| 예 | 결과 |
|---|---|
product('ABCD', repeat=2) |
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD |
permutations('ABCD', 2) |
AB AC AD BA BC BD CA CB CD DA DB DC |
combinations('ABCD', 2) |
AB AC AD BC BD CD |
combinations_with_replacement('ABCD', 2) |
AA AB AC AD BB BC BD CC CD DD |
import sys, itertools
heights = [int(sys.stdin.readline().strip()) for _ in range(9)]
for h in itertools.combinations(heights, 7):
if sum(h) == 100:
h = sorted(h)
print(*h)
break
생각나서 찾아서 만들어본 조합을 구하는 c++ 코드
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> combs;
void comb(vector<int> &arr, vector<int> &picked, int r, int start)
{
if (r == 0)
{
combs.push_back(vector<int>(picked));
return;
}
if (start == arr.size())
{
return;
}
comb(arr, picked, r, start + 1); // 안 뽑는 경우
picked.push_back(arr[start]);
comb(arr, picked, r - 1, start + 1); // 뽑는 경우
picked.pop_back();
}
/* 조합의 경우의 수를 구하는 함수 */
int combN(int n, int r){
if(n == r || r == 0) return 1;
return combN(n-1, r-1) + combN(n-1, r);
}
int main()
{
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> tmp;
const int r = 4;
comb(v, tmp, r, 0);
for (auto k : combs)
{
for (auto u : k)
{
cout << u << " ";
}
cout << "\\n";
}
cout << combs.size() << " == " << combN(v.size(), r) << " ?! \\n";
}
순열
https://ansohxxn.github.io/algorithm/permutation/
#include <iostream>
using namespace std;
void swap(char& a, char& b)
{
char temp = a;
a = b;
b = temp;
}
void permutation(char data [], int depth, int n, int r)
{
if (depth == r)
{
for(int i = 0; i < r; i++)
cout << data[i] << " ";
cout << endl;
return;
}
for(int i = depth; i < n; i++)
{
swap(data[depth], data[i]); // 스왑
permutation(data, depth + 1, n, r); // ⭐재귀
swap(data[depth], data[i]); // 다시 원래 위치로 되돌리기
}
}