Programming 기초/Python
-
[Python 자료구조 #큐1] 선형 큐, 원형 큐, 너비우선탐색Programming 기초/Python 2023. 5. 10. 23:55
* 큐(queue) 선입선출(First-In First Out: FIFO)의 자료구조이다. 실시간 비디오 스트리밍에서 다운로드 된 데이터가 비디오를 재생하기에 충분하지 않으면 큐에 순서대로 모아두었다가 충분한 양이 되었을 때 비디오를 복원하여 재생하는데 이것을 버퍼링(buffering)이라고 한다. * 선형 큐 삭제 연산(pop)의 시간 복잡도는 O(n)이다. 비효율적이다. 삭제연산을 O(1)로 동작하도록 구현한 것이 원형 큐다. items = [ ]# 선형 큐 # 선형 큐 ADT(추상 자료형) def isEmpty():# 큐가 비어있는지 확인 return len(items) == 0 def enqueue(item):# 항목 x를 큐의 맨 뒤에 추가한다. items.append(item) def dequ..
-
[Python 자료구조 #스택3] 미로 탐색Programming 기초/Python 2023. 5. 10. 02:06
* 깊이 우선 탐색(Depth-First-Search, DFS) * 너비 우선 탐색(Breadth-Firs-Search, BFS) * 미로탐색 알고리즘 from Stack import * def isValidPos(x, y): if x = MAZE_SIZE or y >= MAZE_SIZE: return False else: return map[y][x] == "0" or map[y][x] == "x"# (x,y)는 리스트에서 [y][x]가 된다. def DFS(): stack = Stack() stack.push((0, 1)) print("DFS: ") while not stack.isEmpty(): here = stack.pop() print(here, end="->"..
-
[Python 자료구조 #스택2] 스택을 이용한 중위표기 수식의 후위표기 변환Programming 기초/Python 2023. 5. 6. 14:55
* 후위표기 수식 계산 구현 def evalPostfix(expr): s = Stack() for token in expr: if token in "+-*/": val2 = s.pop() val1 = s.pop() if (token == '+'): s.push(val1 + val2) elif (token == '-'): s.push(val1 - val2) elif (token == '*'): s.push(val1 * val2) elif (token == '/'): s.push(val1 / val2) else: s.push(float(token)) return s.pop() * 연산자(Operator) 우선순위 반환 함수 def precedence(op):# op는 operator의 약자 if op == ..
-
[Python 자료구조 #스택1] 소스 파일에서 괄호 검사Programming 기초/Python 2023. 5. 6. 03:54
1. 스택을 클래스로 구현하고 2. 파일 내에서 괄호를 검사하는 checkBracketsV2() 함수를 정의. 3. 파일을 읽기모드로 열어서 줄 단위로 리스트를 만들고 4. 만들어진 리스트에 checkBracketsV2() 함수를 호출하여 검사한다. 아래 코드블럭에서는 소스파일 대신 txt파일을 불러왔다. class Stack: def __init__(self): self.top = [] def __str__(self): return str(self.top) def isEmpty(self): return len(self.top) == 0 def size(self): return len(self.top) def clear(self): self.top = [] def push(self, item): self..
-
[Python 기초 #10] 예외 처리Programming 기초/Python 2023. 4. 27. 16:54
* try try: ... except [발생 오류[as 오류 메시지 변수]]: ... else: # 오류 발생하지 않은 경우 실행 (try가 참값일 때) ... finally: # 무조건 마지막에 실행 여기서 [ ] 기호는 괄호 안의 내용을 생략할 수 있다는 관례 표기법이다. except 발생 오류: 는 오류가 발생했을 때 except문에 미리 정해 놓은 오류 이름과 일치할 때만 except 블록을 수행한다는 뜻이다. except 발생 오류 as 오류 메시지 변수: 는 오류메시지의 냉요을 알고 싶을 때, 발생오류를 지정한 오류 메시지 변수에 담는 것이다. try: 4/0 except ZeroDivisionError as e: print(e) ----------------------------------..
-
[Python 기초 #9] 패키지Programming 기초/Python 2023. 4. 27. 15:45
* 패키지(Packages) 도트(.)를 사용하여 파이썬 모듈을 계층적(디렉터리 구조)으로 관리할 수 있게 해준다. * 패키지 만들기 예) game 패키지의 구조 game/ _ _init_ _.py sound/ _ _init_ _.py echo.py wav.py graphic/ _ _init_ _.py screen.py render.py play/ _ _init_ _.py run.py test.py 여기서 gmae, sound, graphic, play는 디렉터리 이름이고 확장자가 .py인 파일은 파이썬 모듈, game 디렉터리가 이 패키지의 루트 디렉터리이고 sound, graphic, play는 서브 디렉터리이다. 1. 서브 디렉터리(폴더)를 만들고 빈 파일의 모듈을 만들어 놓는다. 2. echo모듈..
-
[Python 기초 #8] 모듈Programming 기초/Python 2023. 4. 25. 19:56
* 모듈 모듈이란 함수나 변수 또는 클래스를 모아 놓은 파일이다. 모듈은 다른 파이썬 프로그램에서 불러와 사용할 수 있게끔 만든 파이썬 파일이라고도 할 수 있다. 파이썬 확장자 .py로 만든 파이썬 파일은 모두 모듈이다. * import 이미 만들어 놓은 파이썬 모듈을 사용할 수 있게 해주는 명령어이다. 예로, mod1.py 파일에 있는 add 함수를 사용하기 위해서는 mod1.add처럼 모듈 이름 뒤에 '.'(도트 연산자)를 붙이고 함수 이름을 쓰면 된다. 모듈 이름 없이 함수 이름만 쓰고 싶은 경우에는 'from 모듈 이름 import 모듈 함수1, 함수2, ...'를 사용하면 된다. ' from 모듈 이름 improt * '로 *문자를 사용하면 해당 모듈의 모든 함수를 불러서 사용한다는 뜻이다. <..
-
[Python 기초 #7] 클래스, 객체와 인스턴스 차이, 생성자, 상속, 오버라이딩Programming 기초/Python 2023. 4. 21. 18:27
* 클래스(class) 클래스는 거푸집과 같다. 같은 기능을 하는 함수를 필요할 때마다 찍어내는 '함수 틀'이다. 클래스로 생성된 함수들을 객체(object)라고 부른다. c언어에는 클래스가 없다. c언어에서는 같은 기능을 하는 함수라도 매번 이름을 약간씩 바꿔가면서 새롭게 정의해야한다. 클래스 이름을 지을 때, 관례적으로 첫 글자를 대문자를 사용한다. 클래스 안에 구현된 함수는 메서드(Method)라고 부른다. 파이썬 메서드의 첫 번째 매개변수 이름은 관례적으로 self를 사용한다. 객체를 호출할 때 호출한 객체 자신이 전달되기 때문에 self를 사용한 것이다. 객체와 인스턴스(instance)의 차이 클래스로 만든 객체를 인스턴스라고도 한다. a =Cookie() 이렇게 만든 a는 객체이다. 그리고 ..