Python으로 알고리즘 풀기

maintain·2020년 11월 25일
0

python으로 알고리즘을 풀 때 도움되는 함수들을 몇 가지 모아봤습니다.

1. enumerate

enumarate(iterable)
(0, iter_value), (1, iter_value) ...

0부터의 숫자(인덱스)와 iterable의 요소들을 묶은 튜플을 반환하는 iterator를 만들어줍니다.

# 실행
for idx, v in enumerate('abcd'):
    print(f'{idx} {v}')
# 결과
0 a
1 b
2 c
3 d
    

2. map

map(callable, iterable)
callable(iter_value0), callable(iter_value1) ...

iterable의 모든 요소를 입력으로 사용해 callable을 실행한 결과를 묶어 반환하는 iterator를 만들어줍니다.

3. functools.cache && functools.lru_cache

@cache
def fnc(input):
@lru_cache(max_size)
def fnc(input):

자동으로 캐싱함수로 만들어주는 데코레이터입니다. 아주 쉽게 동적 프로그래밍 혹은 메모이제이션을 구현할 수 있습니다. lru_cache의 max_size가 None일 경우 캐시 제한이 없어집니다.

4. functools.reduce && itertools.accumulate

reduce(callable, iterable, initializer)
accumulate(callable, iterable, initializer)

reduce의 경우 total, value를 받는 callable로 값을 계속 갱신해서 최종값을 얻습니다. accumulate는 이 과정의 중간값이 모두 포함된 iterable을 반환합니다. initializer가 없으면 첫 번째 값이 그 역할을 하게 됩니다. 다음처럼 쓸 수 있습니다.

# 실행
results = ['a', 'b', 'c']
reduce(lambda total, x: f'{total} {x}', results, ' ')
accumulate(lambda total, x: f'{total} {x}', results)
# 결과
' a b c'
['a','a b', 'a b c']

5. itertools.filterfalse && itertools.compress

filterfalse(callable, iterable)
compress(iterable a, iterable b)

iterable의 값을 받아 callable에 넘겨 false인 것만 가진 새 iterable을 반환합니다. compress는 b의 값이 참인 a값을 반환합니다. 후술할 zip 처럼 개수가 더 적은 것까지만 반환합니다.

[x for x in filterfalse(lambda x: True if x%2==0 else False, [1,2,3,4])]
[x for x in compress(['a','b','c','d'], [0,1,0,1,0])]
# 결과
['b', 'd']

6. zip && itertools.zip_longest

zip(iterable*)
zip_longest(iteratble*, fillvalue=None)

여러 iterable의 각 요소들을 모은 튜플들을 반환합니다. zip의 경우 가장 적은 iterable의 개수까지만 반환하고, zip_longest의 경우 가장 긴 것까지 반환하고 빈 경우엔 fillvalue를 채워 넣습니다.

참고

https://python.flowdas.com/library/itertools.html
https://docs.python.org/ko/3/library/functools.html
가장 쓸만하다고 여겨지는 것들만 모아서 작성하였습니다. 추가적인 정보는 위 링크에서 얻을 수 있습니다. 개인공부 목적으로 작성하였습니다. 틀린 부분이 있다면 댓글로 남겨주시면 감사하겠습니다.

0개의 댓글