본문 바로가기

About/Python

(25)
[Python] fucntools.lru_cache() - 함수의 결과 캐싱 파이썬의 표준 라이브러리에 있는 functools.lru_cache() 는 함수의 결과를 캐시해 주는 함수 데커레이터입니다. 같은 인수를 전달했던 호출 결과가 이미 캐시되어 있으면 함수를 실행하지 않고 캐시 결과를 반환합니다. 함수의 인수와 결과는 딕셔너리를 이용해서 연결하기 때문에 @lru_cache()를 붙인 함수의 인수는 숫자, 문자열, 튜플과 같이 딕셔너리의 key로 사용할 수 있는 객체를 사용해야 합니다. 예시 n번째 피보나치 수를 반환하는 함수 my_fibo() 함수는 재귀함수로 구현되어 있습니다. n이 커질수록 엄청나게 많은 함수가 중복되어 실행되기 때문에 실행 시간이 오래걸리게 됩니다. 1 2 3 4 5 6 7 8 9 10 11 from time import time def my_fibo(..
[Python] IPython을 사용한 Unix/Linux 셸 명령어 실행 - (IPython.utils.SList에 대하여) https://ipython.org/ Jupyter and the future of IPython — IPython IPython provides a rich architecture for interactive computing with: A powerful interactive shell. A kernel for Jupyter. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into your own projects. E ipython.org IPython 설치는 설치 프로그램에 따라 다음과 같이 설치합니다. brew install ipython conda..
[Programmers] k진수에서 소수 개수 구하기(Python 풀이) - 2022 KAKAO BLIND RECRUITMENT https://programmers.co.kr/learn/courses/30/lessons/92335 코딩테스트 연습 - k진수에서 소수 개수 구하기 문제 설명 양의 정수 n이 주어집니다. 이 숫자를 k진수로 바꿨을 때, 변환된 수 안에 아래 조건에 맞는 소수(Prime number)가 몇 개인지 알아보려 합니다. 0P0처럼 소수 양쪽에 0이 있는 경우 P0처럼 소 programmers.co.kr 풀이 1. k진수로의 변환 1 2 3 4 5 6 def to_k_number(n, k): # n을 k진수로 반환 ret = "" while n > 0: ret += str(n % k) n = n // k return ''.join(reversed(ret)) cs 입력 값 n이 0보다 큰 값을 가지는 동안 n을 ..
[Python] 프로퍼티(Property)-getter, setter, deleter 프로퍼티(property) - 인스턴스 메서드를 인스턴스 변수와 같이 다룸 프로그램을 작성하다 보면 인스턴스 변수의 값을 사용하거나 확인하고 싶은 경우가 있습니다. 예를들어 전자상거래 프로그램에서 할인을 할 때 할인 후 가격은 원래 가격에서 계산해서 반환해야하며, 할인율(%)에 음숫값이나 100을 넘는 값을 설정했을 때는 에러처리를 해야합니다. 파이썬에서는 이런 요청을 실현하기 위한 구조로서 프로퍼티(property) 를 제공합니다. 다음 코드는 실제 프로퍼티 를 사용한 예제입니다. class Book: def __init__(self, raw_price): if raw_price book = Book(2000) >>> book.discounts # 초기 할인율 0 0 >>> book.price # 초기..
[Python] 함수 실행 시간 측정 (Python decorator 활용) decorator 함수 정의 def logging_time(original_fn): import time from functools import wraps @wraps(original_fn) def wrapper(*args, **kwargs): start_time = time.time() result = original_fn(*args, **kwargs) end_time = time.time() print("WorkingTime[{}]: {} sec".format(original_fn.__name__, end_time - start_time)) return result return wrapper logging_time() 함수 사용 @logging_time def func(): ... 함수 내용 ... ..
[Python] Iterable & Iterator iter 함수 개발을 하다 보면 하나 이상의 값을 저장하고, 저장된 값들을 불러오는 일은 매우 흔하고 중요하다. Python에서는 다음과 같이 for loop을 기반으로 이러한 작업을 수행한다. numbers = [1, 2, 3, 4] for i in numbers: #numbers에 저장된 내용을 하나씩 출력 print(i, end = ' ') 위의 방법만으로도 대부분의 작업을 수행할 수 있지만, 조금 더 유연한 방법이 있다. numbers = [1, 2, 3, 4] ir = iter(numbers) #iterator 객체를 얻는 방법 print(next(ir)) # next(ir) : iterator 객체를 통해 값을 하나 가져옴(첫번째 값) print(next(ir)) # 두 번째 값 반환 후 출력..
[Python] Counter (단어 개수 세기) Counter Sequence Type의 Data element들의 개수를 dict 형태로 반환하는 객체 collections로 부터 import 하여 사용 from collections import Counter 컨테이너에 동일한 값이 몇 개있는지 쉽게 파악할 수 있다. from collections import Counter c = Counter() c = Counter('CocaCola') print(c) Dict type, keyword parameter 등 모두 처리 가능하다. dict를 이용하여 단어들의 개수를 지정하여 원하는 단어를 원하는 개수만큼 가지는 리스트를 생성할 수 있다. from collections import Counter d = {'red' : 4 , 'blue' : 2 } ..
[Python] Collections - defaultdict (단어 개수 세기) defaultdict Dict type의 값에 기본 값을 지정할 수 있는 dictionary 클래스 Dict의 신규 값 생성 시 유용한다. from collections import defaultdict 기존의 Dict d = dict() print(d['first']) 기본 dict를 사용하게 되면 key = 'first'인 item이 없기 때문에 출력하였을 때 에러가 발생한다. defaultdict 사용 from collections import defaultdict d = defaultdict(lambda : 0) #Default 값을 0으로 지정 print(d['first']) 하지만 defaultdict를 이용하여 기본 값을 0으로 지정하고 출력하였을 때 key = 'first'인 아이템을 추가..
[Python] Collections - OrderedDict OrderedDict 기본 딕셔너리와 거의 비슷하지만, 입력된 아이템들의 순서를 기억하는 Dictionary 클래스 즉 Dict와 달리, 데이터를 입력한 순서대로 dict를 반환함 collections로 부터 import 하여 사용 from collections import OrderedDict 기존 Dict 예시 d = {} d['Hello'] = 100 d['How'] = 200 d['are'] = 300 d['you'] = 500 print(d) v = {} v['How'] = 200 v['are'] = 300 v['you'] = 500 v['Hello'] = 100 print(v) if(d == v): print("두 Dictionary가 동일하다") 두 Dictionary의 입력 순서를 다르게 ..
[Python] Collections - deque Python Collections List, Tuple, Dict에 대한 Python Built-in 확장 자료 구조(모듈) 편의성, 실행 효율 등을 사용자에게 제공함 다음과 같은 모듈이 존재한다. from collections import deque from collections import Counter from collections import OrderedDict from collections import defaultdict from collections import namedtuple Deque Stack과 Queue를 지원하는 모듈 List에 비해 효율적인 자료 저장방식을 지원함 collections로 부터 import하여 사용 from collections import deque 기본적으로..