PYTHON
[Python] enumerate, zip, permutations, combinations
미소서식지
2023. 6. 11. 12:01
enumerate
def func_b(exp):
for index, value in enumerate(exp): # "123+45" (0, '1') (1, '2') (3, '3) (4, '+')
print(index, value)
if value == '+' or value == '-' or value == '*':
return index
문자열 -> 리스트에 하나씩 넣기
def solution(num):
# Write code here.
# num + 1 한 것에서 0은 1로 바꾼 것 return
num += 1
answer = list(str(num)) # '663' -> ['6', '6', '3']
for idx, n in enumerate(answer):
if n == '0':
answer[idx] = '1'
result = int(''.join(answer))
return result
리스트 문자열로 합치기
string_list = ['1', '2', '2', '3']
print(' '.join(string_list)) ## 공백 한칸을 구분자로 한다.
# 1 2 3 4
permutaions (순열)
뽑힌 순서에 의미를 둔다.
즉 똑같은 값이 뽑히더라도 순서가 다르면 다른 경우의 수로 취급한다. [1, 2] != [2, 1]
permutations(반복가능한 객체, 뽑는 개수)
from itertools import permutations
for i in permutations([1,2,3,4], 2):
print(i, end=" ")
# (1, 2) (1, 3) (1, 4) (2, 1) (2, 3) (2, 4) (3, 1) (3, 2) (3, 4) (4, 1) (4, 2) (4, 3)
combinations (조합)
순서를 고려하지 않는다. 따라서 (1, 2)와 (2, 1) 은 다른 경우의 수가 아니므로 (1, 2)만 결과로 나온다.
combinations(반복가능한 객체, 뽑는 개수)
from itertools import combinations
for i in combinations([1,2,3,4], 2):
print(i, end=" ")
# (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)
product (중복 순열)
순열이기 때문에 순서를 고려하는데, 같은 수를 r번 뽑을 수 있다.
product(반복 가능한 객체, repeat = r번 뽑을 수 있음)
for i in product([1,2,3], repeat=2):
print(i, end=" ")
# (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)
combinations_with_replacement (중복 조합)
조합이기 때문에 순서를 고려하지 않는 것은 맞지만, 같은 수를 r번 뽑을 수 있다는 차이가 있다.
combinations_with_replacement(반복 가능한 객체, r번 뽑을 수 있음)
from itertools import combinations_with_replacement
for cwr in combinations_with_replacement([1,2,3,4], 2):
print(cwr, end=" ")
# (1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)