Contents
1 Python’s Sequence Types
2 Low-Level Arrays
컴퓨터 메모리에서 배열을 어떻게 관리할까?
→ 한 칸이 bytes를 표현, 배열은 연속적인 순서로 변수들의 그룹을 저장한다.
Python internally represents each Unicode character (e.g. “SAMPLE”) with 16 bits (i.e., 2 bytes). 6 characters would be stored in 12 consecutive bytes of memory.
→ 2146~2157 저장.
2-1 Referential Arrays
3 Dynamic Arrays and Amortization
Dynamic Arrays
예시) 2146 부터 2157까지 쓰겠다.
이와 같은 특징은, 데이터를 중간에 변경하는 것 뿐만 아니라, 추가하고 삭제하는 것도 제한되는 것을 의미한다.
이 때, 파이썬의 list class는 흥미로운 기능을 제공한다. 처음에 유저가 길이를 제한했다고 하더라도, element를 리스트에 더 추가하고자 한다면 reserved된 capacity가 만료된다. 파이썬은 이와같은 추상화를 제공하는데 이게 흔히 알려진 dynamic array이다.
리스트 클래스의 strategy를 알아보기 위해 저자들은 empirical한 evidence를 보인다. 다음과 같이 코드를 짜서 시퀀스를 표현할 때 리스트 객체가 차지하는 공간을 살펴보자. (3.2에서 더 자세히)
import sys
data=[]
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
print("Length: {0:3d}; Size in bytes: {i:4d}".format(a, b))
data.append(None)
3.1 파이썬 list class의 구현 형태 정리해보자.
import ctypes # provides low-level arrays
class DynamicArray:
"""A dynamic array class akin to a simplified Python list."""
def init (self):
self._n=0 # count actual elements
self._capacity = 1 # default array capacity
self._A = self._make_array(self._capacity) # low-level array
def __len__(self):
"""Return number of elements stored in the array."""
return self. n
def __getitem__(self, k):
"""Return element at index k."""
if not 0 <= k < self._n:
raise IndexError('invalid index')
return self._A[k] # retrieve from array
def append(self, obj):
"""Add object to end of the array."""
if self._n == self._capacity: # not enough room
self._resize(self._capacity) # so double capacity
self._A[self._n] = obj
self._n += 1
def _resize(self, c): # nonpublic utitity
"""Resize internal array to capacity c."""
B = self.make_array(c) # new (bigger) array
**for k in range(self._n): # for each existing value
B[k] = self._A[k]**
self._A=B # use the bigger array
self._capacity = c
**def _make_array(self, c): # nonpublic utitit
"""Return new array with capacity c."""
return (c ctypes.py object)()**
# pop method 추가
def pop(self, k): # index number
""" Return pop item and remove k in array."""
item = self._A[k]
for j in range(k, self._n-1): # self._n : actural elements 1->1
self._A[j] = self._A[j+1]
self._n -= 1
return item
3.2 Amortized Analysis of Dynamic Arrays
*None is a special constant in Python that represents the absence of a value or a null value. (None 은 singleton 패턴)
4 Python’s List and Tuple Classes
→ k denote the leftmost index at which they disagree or else k = min(,).
String class
5 Using Array-Based Sequences
Storing High Scores for a Game
A sequence of objets 이 저장되어야 할 때, 배열 기반의 자료구조를 이용해서 저장해보자.
GameEntry 클래스를 만들어 객체마다 score나 name을 반환하는 메소드를 구현하자.
이런 객체를 우리는 Scoreboard 를 만들어 저장하고, 이 스코어 보드는 가장 높은 점수를 제한하여 저장할 수 있도록 한다.
→ 다음과 같은 모양이 될 것이다.
Sorting a Sequence
def insert_sort(arr):
for i in range(1, len(arr)):
temp = arr[i]
j = i
while j > 0 and temp < arr[j-1]:
arr[j] = arr[j-1]
j-=1
arr[j] = temp
return arr
6 Multidimensional Data Sets
- [[0]*3 for _ in range(3)] → **O**
Tic-Tac-Toe
3X3 보드, 2명의 게임자
X와 O를 보드에 번갈아가며 마크함.
X부터 시작.
어느 한 사람이, 가로-세로-대각선 을 자신의 마크로 모두 채우면 이김.
코드 (p.223)
game = TicTacToe()
game.mark(i,j) # 순서대로 서로 입력.
print(game) # __str__
winner = game.wineer()
if winner is None:
print("Tie") # 비긴경우.
else:
print(winner, "wins")
Exercise
연습문제는 아래 링크에서 확인 가능하다.
Term definition
Immutable or mutable?
The capacity of an array cannot trivially be increased by expanding into subsequent cells. → Immutable
The class allows us to add elements to the list with no apparent limit on the overall capacity of the list. → Mutable