티스토리 뷰
📌 곱집합(Cartesian product) 구하기 - product
for문을 사용하여 구하는 방법
iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'
for value1 in iterable1:
for value2 in iterable2:
for value3 in iterable3:
print(value1, value2, value3)
itertools.product를 사용하여 구하는 방법
import itertools
iterable1 = 'ABCD'
iterable2 = 'xy'
iterable3 = '1234'
print(list(itertools.product(iterable1, iterable2, iterable3)))
📌 2차원 리스트를 1차원 리스트로 만들기 - from_iterable
문자열을 담은 2차원 리스트를 1차원 리스트로 반환
내가 쓴 코드
def solution(mylist):
answer = []
for i in mylist:
# 방법 1
answer += element
# 방법 2
for j in i:
answer.append(j)
return answer
for문을 사용하지 않는 방법
my_list = [[1, 2], [3, 4], [5, 6]]
# 방법 1 - sum 함수
answer = sum(my_list, [])
# 방법 2 - itertools.chain
import itertools
list(itertools.chain.from_iterable(my_list))
# 방법 3 - itertools와 unpacking
import itertools
list(itertools.chain(*my_list))
# 방법 4 - list comprehension 이용
[element for array in my_list for element in array]
# 방법 5 - reduce 함수 이용 1
from functools import reduce
list(reduce(lambda x, y: x+y, my_list))
# 방법 6 - reduce 함수 이용 2
from functools import reduce
import operator
list(reduce(operator.add, my_list))
# 방법 7 - numpy 라이브러리의 flatten 이용
# 리스트 내 각 원소의 길이가 동일한 경우에만 사용 가능
import numpy as np
np.array(my_list).flatten().tolist()
📌 순열과 조합 - combinations, permutations
순열은 itertools.permutation를 통해서, 조합은 itertools.combinations를 통해서 구할 수 있다.
itertools.permutation(iterable, r) : if r is not specified or is None, r defaults to the length of the iterable
import itertools
pool = ['A', 'B', 'C']
print(list(map(''.join, itertools.permutations(pool)))) # 3개의 원소로 수열 만들기
print(list(map(''.join, itertools.permutations(pool, 2)))) # 2개의 원소로 수열 만들기
📌 가장 많이 등장하는 알파벳 찾기 - counter
내가 쓴 코드
my_str = input().strip()
count = {}
max = 0
for i in my_str:
if i in count:
count[i] += 1
else:
count[i] = 1
if count[i] > max:
max = count[i]
mylist = []
for key in count:
if max == count[key]:
mylist.append(key)
mylist.sort()
str = ''
for i in mylist:
str += i
print(str)
수정한 코드
import collections
my_str = input().strip()
c = dict(collections.Counter(my_str))
max = 0
str = ''
for i in c:
if c[i] > max:
c[i] = max
for i in c:
if c[i] == max:
str += i
print(''.join(sorted(str)))
most_common을 이용한 코드
c = collections.Counter(my_str)
str = ''
max = c.most_common(1)[0][1]
for i in c.most_common():
if i[1] == max:
str += i[0]
print(''.join(sorted(str)))
for문을 이용하는 경우 코드가 복잡해진다.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = {}
for number in my_list:
try:
answer[number] += 1
except KeyError:
answer[number] = 1
print(answer[1]) # = 4
print(answer[3]) # = 3
print(answer[100]) # = raise KeyError
python의 collections.Counter를 이용하면 간단한 코드를 만들 수 있다.
import collections
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 7, 9, 1, 2, 3, 3, 5, 2, 6, 8, 9, 0, 1, 1, 4, 7, 0]
answer = collections.Counter(my_list)
print(answer[1]) # = 4
print(answer[3]) # = 3
print(answer[100]) # = 0
프로그래머스 - 파이썬을 파이썬답게 강의를 듣고 정리한 내용
programmers.co.kr/learn/courses/4008
'python' 카테고리의 다른 글
| flag or for-else (0) | 2021.04.03 |
|---|---|
| List comprehension의 if 문 (0) | 2021.04.03 |
| sequence types 다루기 - join, sequence type의 * 연산 (0) | 2021.03.06 |
| iterable 다루기 - sorted, zip, map (0) | 2021.03.06 |
| 문자열 다루기 - ljust/center/rjust, string module (0) | 2021.03.06 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 출력 형식 지정
- 이진 탐색
- divmod
- rjust
- 선형 배열
- 선형 탐색
- sequence type
- for-else
- springboot
- ValidataionUtils
- valid annotation
- djnago
- 스택
- 자료구조
- 파이썬
- Django
- ljust
- python flag
- airbnb clone
- most_common
- tailwind
- Stack
- initBinder
- 의존 주입
- postfix notation
- 직접 주입
- string module
- python
- 양방향 연결 리스트
- 스프링부트
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
글 보관함
