practivceAlgorithm/PYTHON 기능연습 11

[Python] Python List, Dictionary, Set등 참조형 자료구조 복사

Python의 List와 Set, Dictionary등은 call by reference한다. 즉 a = [1, 2, 3] b = a b.append(4) print(a) # [1, 2, 3, 4] 할당 된 주소가 공유된다. 때문에 자료형 a 와 동일한 자료형 b를 만들기 위해 다음과 같은 방법을 사용할 수 있다. from copy import copy, deepcopy l = [1, 2, 3] s = {1, 2, 3} d = {1:1, 2:2, 3:3} # use copy(얕은복사) l_copy = copy(l) s_copy = copy(s) d_copy = copy(d) # use deepcopy(깊은 복사) l_deepcopy = deepcopy(l) s_deepcopy = deepcopy(s) d..

[Python] 메소드 별 입출력 속도 비교

파이썬 입출력 속도 비교. 입력속도 1 PyPy int(sys.stdin.readline()) 0.9229 2 PyPy map(int,os.read(0, 100000000).split('\n')) 1.1169 3 PyPy3 map(int,os.read(0, 100000000).decode('utf-8').split('\n')) 1.5408 4 PyPy int(raw_input()) 1.925 5 Python 3 map(int,os.read(0, 100000000).decode('utf-8').split('\n')) 4.4033 6 Python 3 int(sys.stdin.readline()) 4.4394 7 PyPy3 int(sys.stdin.readline()) 6.6291 8 Python 3 int(..

[문자열 뒤집기] 문자열 슬라이싱

인덱스를 지정하면 해당 위치의 배열 포인터를 얻게된다. 이를 통해 연결된 객체를 찾아 실제 값을 찾아낸다. 슬라이싱 0.499 마이크로초 1 리스트 reverse() 2.46 마이크로초 5 revsered() + join() 2.49 마이크로초 6 for 반복 5.5 마이크로초 12 while 반복 9.4 마이크로초 21 재귀 24.3 마이크로초 54 s[:]는 사본을 리턴한다. 이 방식은 문자열이나 리스트를 복사하는 파이썬다운 방식(Pythonic way) 이다. 앞으로 문자열 비교는 slicing을 이용하자.

파이썬 개인적으로 기억해야 할 것 정리(210721)

​ 순서는 그냥 쓰는대로 썼음 1. lambda ​ 수업듣고 이해하게 됐음. 함수를 표현식형태로 다른곳에 인자로 쓰기위한 느낌. ​ lambda 매개변수 리턴값 뒤에 조건문 오던 말던. ​ sorted의 key값으로 쓰면 매우 유용함. sorted(list, lambda x: (x[1],x[0]),reverse=True) ​ => 2번째 열, 1번째 열 순으로 이중정렬을 할수도있음. ​ sorted(dict,lambda x: dict[x]/[2])로 key값 대신서 index값 같고 key다른 여러값 동시에 뽑아 리스트로 만들수도있음. 2. map,reduce,filter ​ 앞에 설명한 lambda를 쓰기 가장 좋은 함수를 인자로 받는 메소드들. ​ map,filter은 (함수,리스트)를 인자로 받고 ..

[Python] 특정 문자열 찾기.(find응용)

1. find 2. 여러개 탐색. a = str1.find(str2) print a while str1[a+1:].find(str2) != -1: a = str1[a+1:].find(str2) + a + 1 print a 3. re 모듈의 finditer(b,a) for a in re.finditer(str2,str1) : print a.start() start()는 시작위치 반환, end()는 끝위치 반환 4. A.startswitth(a,b) a문자가 A문자열의 b위치에서 시작되면 True반환. 5. A.endswith(a,b) =>보통 b위치에 find(a)를 넣어 True강제반환하게끔 가능.

[Python] itertools 순열, 조합 구현.

itertools라이브러리 combinations모듈과 permutations모듈을 통해 손쉽게 순열과 조합을 구할 수 있다. 이때 만들어진 순열,조합은 튜플형태로 리스트에 담겨서 반환된다. [(0,1,2),...] 조합 from itertools import combinations arr = [0, 1, 2, 3, 4, 5] print(list(combinations(arr, 3))) 순열 from itertools import permutations arr = [0, 1, 2, 3, 4, 5] print(list(permutations(arr, 3))) 재귀 기본적인 아이디어는 DFS,백트래킹과 유사하다. combination([0,1,2,3],2) = ([0],combination([1,2,3],1..

[PYTHON] call by value? call by reference?

Passed by assignment. 즉 어떤 값을 전달하느냐에 따라 달라진다. num = 10 메모리에 저장된 10이라는 정수형 객체를 num이라는 변수가 가리킨다. 파이썬은 int, str, tuple,dictionary의 key는 immutable하고 list, dict는 mutable하다. (dict value는 마찬가지로 자료형에따라 달라짐) immutable은 call by value 즉 value만 가져와 새 메모리에 객체를 담는다는 뜻. mutable은 기존 메모리를 가르킨다는 뜻. 즉 list와 dictionary는 변수명을 바꿔서 담아준다 하더라도 하나가 변하면 모든 변수의 값이 변하게 된다. (메모리에 담긴 본체가 변하므로) 이때 list같은 경우 c = a[:] 즉 슬라이스로 재정..