파일이름으로 디렉토리인지 확인

import os os.path.isdir(full_filename) 참고 자료 https://wikidocs.net/39

2024-09-15 · 1 min · 6 words

파일 이름에서 확장자 분리

splitext 함수를 호출하고 마지막 요소가 확장자가 된다. import os ext = os.path.splitext(full_filename)[-1] 참고 자료 https://wikidocs.net/39

2024-09-15 · 1 min · 15 words

특정 디렉토리의 하위 디렉토리 검색

os.walk() 함수를 사용하면 된다. import os for (path, dir, files) in os.walk("c:/"): for filename in files: ext = os.path.splitext(filename)[-1] if ext == '.py': print("%s/%s" % (path, filename)) 참고 자료 https://wikidocs.net/39

2024-09-15 · 1 min · 30 words

특정 디렉토리의 파일 리스트

import os os.listdir(dirname) 참고 자료 https://wikidocs.net/39

2024-09-15 · 1 min · 6 words

이터레이터, 제너레이터, yield

이터레이터(iterator) 이터레이터는 값을 차례대로 꺼낼 수 있는 객체다. 우리가 for 반복문을 사용할 때 요소를 하나씩 꺼내서 처리할 수 있게 되는데, 이터레이터를 사용했기 때문에 가능한 것이다. 어떤 클래스가 이터레이터이기 위해서는 다음 조건을 만족해야된다. __iter__ 메소드를 구현하되 자기 자신(self)을 반환한다. __next__ 메소드를 구현해서 next 내장 함수의 인자로 자신을 줬을 때 다음에 반환할 값을 정의해야된다. 더 이상 반환할 값이 없는 경우 __next__메소드는 StopIteration 예외를 일으키도록 한다. 이터러블(iterable) 말 그대로 ‘순회 가능한’이라는 뜻이다. for 문의 in 키워드 뒤에 올 수 있는 모든 값을 이터러블이다....

2024-09-15 · 2 min · 291 words

우선순위 큐 사용법

queue 내장 모듈에 구현이 되어있다. from queue import PriorityQueue que = PriorityQueue() que.put(4) que.put(1) que.put(7) que.put(3) print(que.get()) # 1 print(que.get()) # 3 print(que.get()) # 4 print(que.get()) # 7 참고 자료 https://www.daleseo.com/python-priority-queue/

2024-09-15 · 1 min · 31 words

상속시 부모의 메서드 호출하는 법

super() 를 붙이면된다. class MaxLimitCalculator(Calculator): max_limit = 100 def add(self, val): super().add(val) if self.value > self.max_limit: self.value = self.max_limit 참고 자료 https://dev-ku.tistory.com/168

2024-09-15 · 1 min · 22 words

빠르게 입력 받기

많은 양의 데이터를 입력받아야 될 때 input() 함수가 느릴 수 있다. 이럴 때는 sys 라이브러리의 readline() 함수를 이용하면 된다. rstrip()은 string 오른쪽에 있는 개행 문자와 공백을 제거해주는 역할을 한다. readline()으로 입력하게 되면 문자열에 개행도 포함되기 때문이다. import sys input_data = sys.stdin.readline().rstrip() 참고 자료 https://www.delftstack.com/ko/howto/python/python-remove-newline-from-string/

2024-09-15 · 1 min · 44 words

문자의 ASCII 코드 값 찾기

ord() 함수를 사용하면 된다. character = 'P' unicode_char = ord(character) print(unicode_char) 참고 자료 https://www.programiz.com/python-programming/methods/built-in/ord

2024-09-15 · 1 min · 14 words

디렉토리 경로와 파일이름 합치기

import os os.path.join(dirname, filename) 참고 자료 https://wikidocs.net/39

2024-09-15 · 1 min · 7 words

공백으로 구분해서 입력 여러개 받기

n, m, k = map(int, input().split()) 위와 같이 구현할 수 있다. split()을 통해 공백 단위로 나누어 str의 리스트를 만들게 됩니다. 각 요소를 int형으로 변환하기 위해 map() 을 사용하게 되는데 map()의 리턴 타입은 map 이라는 클래스입니다. 참고 자료 https://www.programiz.com/python-programming/methods/built-in/map https://mjmjmj98.tistory.com/83

2024-09-15 · 1 min · 39 words

가능한 모든 순열 구하기

직접 구현하려고 하는데, 이미 파이썬에서 제공하고 있었다. import itertools inp_list = [4, 5, 6] permutations = list(itertools.permutations(inp_list)) print(permutations) [(4, 5, 6), (4, 6, 5), (5, 4, 6), (5, 6, 4), (6, 4, 5), (6, 5, 4)] 순열 길이의 기본값은 입력 값의 길이가 된다. 만약 길이를 직접 지정하려면 파라미터를 추가하면 된다. import itertools inp_list = [1, 2, 3] permutations = list(itertools.permutations(inp_list, r=2)) print(permutations) [(4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5)] 참고 자료 https://www....

2024-09-15 · 1 min · 77 words

sort 기준 변경

sort() 함수의 key 파라미터를 통해서 정렬 기준을 변경할 수 있다. 이 파라미터는 람다를 파라미터로 받는다. 람다는 요소를 파라미터로 받고, 우선 순위가 높은 정렬 기준을 앞으로 오도록 하는 튜플을 반환하면 된다. 역순으로 정렬하고 싶다면 -x[0] 와 같이 두면 역순으로 정렬된다. temp.sort(key=lambda x : (x[0], x[1])) # '-'부호를 이용해서 역순으로 가능 좀 더 복잡한 비교 연산이 필요한 경우 함수를 사용해야된다. functools 모듈을 불러와서 functools.cmp_to_key() 의 파라미터로 자신이 커스텀한 함수를 주면 된다. 왼쪽의 값이 먼저 오고싶다면 -1을, 오른쪽 값이 먼저 오고싶다면 1을, 같다면 0을 반환하면된다....

2024-09-15 · 1 min · 122 words

range() 역순으로 사용하기

range(start, stop, step) 라는 정의를 사용하면 된다. step이 다음 숫자로 이동하는 변화량이다. range(5, -1, -1) 참고 자료 https://stackoverflow.com/questions/7286365/print-a-list-in-reverse-order-with-range/21714738

2024-09-15 · 1 min · 18 words

Python 기초 문법

참고자료: 점프 투 파이썬 숫자형 출력 print("asdf") 조건문 if if a > 1: print("a is greater than 1") 반복문 for for a in [1, 2, 3]: print(a) 반복문 while while i < 3: i=i+1 print(i) 함수 def add(a, b): return a+b add(3,4) 제곱 a ** b 나누기 7 / 4 나눗셈 몫 7 // 4 문자열 문자열 표현 4가지 "Hello World" 'Python is fun' """Life is too short, You need python""" '''Life is too short, You need python''' 문자열 연결 >>> head = "Python" >>> tail = " is fun!...

2024-09-15 · 20 min · 4181 words

lower_bound, upper_bound 바이너리 서치

python에서 자체적으로 함수로 제공하고 있다. lower_bound: bisect_left(literable, value) upper_bound: bisect_right(literable, value) 참고 자료 https://docs.python.org/3/library/bisect.html

2024-09-15 · 1 min · 14 words