Programming/python
-
Python Class - 5Programming/python 2021. 6. 29. 21:08
Python magic method 혹은 special method라고 불리는 것들이다. 우리는 이미 magic method나 special method를 알고 있다. 왜냐하면 우리가 자주 사용해왔기 때문이다. 결국, 파이썬 내부에 구현된 메소드들을 magic method 혹은 special method라 불린다. magic method의 종류를 보려면 dir 명령어를 이용하며 된다. __로 시작하는 method들이 magic method들이다. dir(int) dir(float)
-
Python Class - 4Programming/python 2021. 6. 29. 21:04
1) NamedTuple 일반적인 tuple을 사용할때는 [0], [1]으로 접근을 해야한다. # 일반적인 튜플 사용 pt1 = (1.0, 5.0) pt2 = (2.5, 1.5) from math import sqrt line_leng1 = sqrt((pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2) 하지만 이름으로 접근해야할때는 어떻게 해야될까? 좌표계 예제인데, [0],[1]이 아닌 x,y로 접근하고 싶다. 이럴때 collections의 namedtuple을 사용하면 된다. # 네임드 튜플 선언 Point = namedtuple('Point', 'x y') # 두 점 선언 pt1 = Point(1.0, 5.0) pt2 = Point(2.5, 1.5) # 계산 lin..
-
Python Class - 3Programming/python 2021. 6. 24. 22:19
왜 클래스의 메소드 앞에는 self가 붙을까? class Student(): # 클래스 변수 student_count = 0 def __init__(self, name, number): # 인스턴스 변수 self._name = name self._number = number Student.student_count += 1 def __str__(self): return 'str {}'.format(self._name) def __repr__(self): return 'repr {}'.format(self._name) def detail_info(self): print('current id = {}'.format(id(self))) print('Student detail info : {} {}'.format..
-
Python Class - 2Programming/python 2021. 6. 24. 22:17
클래스 변수 와 인스턴스 변수 Swift에도 존재하지만, 클래스 변수 : 클래스 전체에서 공유하는 변수 인스턴스 변수 : 생성된 객체 안에서만 공유되는 변수 # 클래스 변수와 인스턴스 변수 # 클래스 변수는 모든 클래스에서 공유, 인스턴스 변수는 생성후 사용 가능 class Student(): # 클래스 변수 student_count = 0 def __init__(self, name, number): # 인스턴스 변수 self._name = name self._number = number Student.student_count += 1 def __str__(self): return 'str {}'.format(self._name) def __repr__(self): return 'repr {}'.form..
-
Python Class - 1Programming/python 2021. 6. 24. 22:16
클래스 구조 : 재사용성 증가, 코드 반복 최소화, 메소드 활용 : magic method의 __str__, __repr__을 자주 활용하자 class Student(): def __init__(self, name, number): self._name = name self._number = number def __str__(self): return 'str : {}, {}'.format(self._name, self._number) def __repr__(self): return 'repr : {}, {}'.format(self._name, self._number) stu1 = Student('Kim', 1) print(stu1.__dict__) # {'_name': 'Kim', '_number': 1}..
-
다익스트라(Dijkstra) 알고리즘Programming/python 2021. 3. 10. 09:51
특정 정점까지 가는데 최소 비용을 찾는 알고리즘이다. 실생활에서 네비게이션에서 빠른길 찾기의 개념과 유사하다. 시작점이 주어지고, 특정 정점까지 오는데 가중치를 최소비용으로 계산하면 된다. distances에 각 정점에 도착하는 최소비용을 저장, 나중에 특정 정점을 꺼내오면 된다. distances는 구현하기 나름이긴한데, 정점이 영문이면 dictionary를 사용하고 숫자면 list를 쓰면 된다. 물론 둘다 dictionary를 사용하기도 한다. 그리고 다익스트라는 힙을 사용해서 구현한다. (python에서는 heapq모듈을 사용하는데, 최소 비용으로 자동 정렬되기 때문이다. 처음에 distances(각 정점에 도달하는 비용)은 무한대로 잡아놓고, 출발점만 0으로 잡는다. 이렇게 하는 이유는 얼마가 최..
-
Bisect ModuleProgramming/python 2021. 3. 9. 11:05
Bisect python에서 제공하는 패키지 이진 탐색을 쉽게 할 수 있도록 하는 함수 배열에서 특정 값을 찾는 방법은 1) for문을 앞에서부터 돌린다. 2) left, right를 둬서 이분 탐색을 한다. bisect는 2)번을 좀 더 쉽게 할 수 있도록 만들어 놓은 함수이다. 예를 들어서 점수에 따른 등급을 찾는다고 해보자 arr = [60, 70, 80, 90] val = ['F', 'D', 'C', 'B', 'A'] print(bisect.bisect_left(arr, 89),bisect.bisect_right(arr, 89), val[bisect.bisect_right(arr, 89)]) # 3 3 B print(bisect.bisect_left(arr, 79), bisect.bisect_ri..