보통의 경우 EOF까지 파일 읽기를 반복한다. f = open('myfile.txt', 'r') while True: line = f.readline() if not line: break raw = line.split() print(raw) f.close() python의 with-as 구문을 이용하면 간결한 코드를 짤 수 있다. 📌 with-as 구문의 장점 with-as 블록이 종료되면 파일이 자동으로 close 되므로 파일을 close 할 필요 없음 readlines가 EOF까지만 읽으므로 while문 안에서 EOF 체크할 필요 없음 파일뿐만 아니라 socket이나 http 등에서도 사용 가능함 프로그래머스 - 파이썬을 파이썬답게 강의를 듣고 정리한 내용 programmers.co.kr/learn/..
📌 인스턴스의 출력형식을 지정하는 방법 1. print문 안에서 format 지정 class Coord(object): def __init__ (self, x, y): self.x, self.y = x, y point = Coord(1, 2) print( '({}, {})'.format(point.x, point.y) ) 2. 클래스 바깥에 출력 함수 생성 class Coord(object): def __init__ (self, x, y): self.x, self.y = x, y def print_coord(coord): print( '({}, {})'.format(coord.x, coord.y) ) print_coord(point) 3. __str__ 메소드를 사용하여 클래스 내부에서 출력 format..
직접 binary search algorithm을 구현하는 경우 (출처 : https://github.com/python/cpython/blob/master/Lib/bisect.py) def bisect(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if a[mid] < x: lo = mid + 1 else: hi = mid return lo mylist = [1, 2, 3, 7, 9, 11, 33] print(bisect(mylist, 3)) python의 binary search module의 bis..
📌 flag or for-else 자연수 5개를 받아, 숫자를 차례로 곱해 나온 제곱수가 되면 found를, 그렇지 않으면 not found 출력 내가 푼 코드 import math numbers = [int(input()) for _ in range(5)] answer = 1 flag = False for number in numbers: answer *= number if math.sqrt(answer) == int(math.sqrt(answer)): flag = True print("found") break if not flag: print("not found") Flag 변수 이용 import math if __name__ == '__main__': numbers = [int(input()) fo..
📌 for 문과 if문을 한번에 정수를 담은 리스트 mylist를 입력받아, 이 리스트의 원소 중 짝수인 값만을 제곱해 담은 새 리스트를 반환 내가 푼 코드 def solution(mylist): answer = [] for number in mylist: if number%2==0: answer.append(number**2) return answer python의 list comprehension을 사용하면 for문과 if문을 한 줄 에 작성할 수 있다 answer = [number**2 for number in mylist if number % 2 == 0] 프로그래머스 - 파이썬을 파이썬답게 강의를 듣고 정리한 내용 programmers.co.kr/learn/courses/4008
📌 곱집합(Cartesian product) 구하기 - product for문을 사용하여 구하는 방법 iterable1 = 'ABCD' iterable2 = 'xy' iterable3 = '1234' for value1 in iterable1: for value2 in iterable2: for value3 in iterable3: print(value1, value2, value3) itertools.product를 사용하여 구하는 방법 import itertools iterable1 = 'ABCD' iterable2 = 'xy' iterable3 = '1234' print(list(itertools.product(iterable1, iterable2, iterable3))) 📌 2차원 리스트를 1차원..
Sequence Type이란 int 타입 인덱스를 통해 원소를 접근할 수 있는 iterable로 list, str, tuple와 같은 것이다. 📌 sequence 멤버를 하나로 이어 붙이기 - join 문자열 리스트를 입력받아 이 리스트의 원소를 모두 이어 붙인 문자열을 리턴하는 함수 작성 내가 푼 코드 def solution(mylist): answer = '' for i in mylist: answer += i return answer join 함수는 문자열의 시퀀스를 연결하는 역할을 한다. join 함수를 이용하여 코드를 간단하게 작성할 수 있다. def solution(mylist): answer = ''.join(my_list) return answer 📌 삼각형 별 찍기 - sequence t..
iterable이란 자신의 멤버를 한 번에 리턴할 수 있는 객체로 list, str, tuple, dictionary와 같은 것이다. 📌 원본을 유지한 채, 정렬된 리스트 구하기 - sorted sort() 함수는 원본의 순서를 변경하기 때문에 deep copy 후 sort를 사용하여 정렬해야 되지만 sorted() 함수는 원본은 그대로 두고 정렬하기 때문에 deep copy가 필요 없다. 📌 2차원 리스트 뒤집기 - zip 2차원 리스트를 인자로 받아 행과 열을 뒤집은 값을 반환하는 함수 작성 input : [[1,2,3], [4,5,6], [7,8,9]] output : [[1,4,7], [2,5,8], [3,6,9]] zip과 unpacking을 이용하여 변환 가능 def solution(mylis..
- Total
- Today
- Yesterday
- 자료구조
- most_common
- 스프링부트
- 이진 탐색
- Stack
- 선형 탐색
- Django
- 출력 형식 지정
- 선형 배열
- 직접 주입
- 스택
- initBinder
- postfix notation
- 양방향 연결 리스트
- ljust
- python
- airbnb clone
- tailwind
- rjust
- springboot
- divmod
- 의존 주입
- valid annotation
- djnago
- sequence type
- 파이썬
- ValidataionUtils
- python flag
- string module
- for-else
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
