Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 동적 배열 구현

<시간/>

동적 배열

파이썬에서 목록, 집합 및 사전은 변경 가능한 객체입니다. 숫자, 문자열 및 튜플은 변경할 수 없는 개체입니다. 변경 가능한 개체는 목록, 집합 또는 사전에서 항목을 추가/삭제하는 것을 의미하지만 튜플 또는 문자열과 같은 변경할 수 없는 개체의 경우에는 그렇지 않습니다.

파이썬에서 목록은 동적 배열입니다. 동적 목록을 만들어 봅시다 -

>>> #Create an empty list, named list1
>>> list1 = []
>>> type (list1)
<class 'list'>
라는 이름의 빈 목록을 만듭니다.

빈 목록 list1 −

에 몇 가지 항목을 추가합니다.
>>> # Add items
>>> list1 =[2, 4, 6]
>>> list1
[2, 4, 6]
>>> # Another way to add items, using append.
>>> list1.append('Tutorialspoint')
>>> list1
[2, 4, 6, 'Tutorialspoint']

목록에서 일부 항목 제거 -

>>> # deleting item from a list
>>> list1.pop()
'Tutorialspoint'
>>> list1
[2, 4, 6]

위에서 우리는 목록이 실제로 배열의 확장임을 알 수 있습니다. 여기서 목록 크기를 수정(증가 또는 축소)할 수 있습니다. 크기가 "0"인 목록으로 시작한 다음 "4" 항목을 추가했습니다.

동적 배열 구현의 기본

목록이 있는 예를 고려하십시오. list1은 배열의 크기가 가득 차면 추가되며 크기 제한 단점을 극복하기 위해 아래 단계를 수행해야 합니다. 이것이 동적 배열 구현의 기초입니다 -

  • 더 큰 용량의 새 어레이 list2 할당
  • list2[i] =list1[i], i =0,1….n-1로 설정합니다. 여기서 n은 항목의 현재 번호입니다.
  • 이제 list2가 새 목록을 참조하므로 list1=list2를 설정합니다.
  • 그런 다음 목록(list1)에 새 항목을 삽입(추가)하면 됩니다.

파이썬 프로그래밍에서 동적 배열 개념을 구현하는 방법에 대한 간단한 코드를 만들어 보겠습니다. 우리는 ctypes 모듈에서 원시 배열로 사용될 ctypes라는 파이썬의 내장 라이브러리 클래스를 사용하여 우리 고유의 동적 배열 클래스를 만들 것입니다.

dynamicArray.py

import ctypes
class DynamicArray(object):
   #Initialize it
   def __init__(self):
      #We'll have three attributes
      self.n = 0 # by default
      self.capacity = 1 # by default
      self.A = self.make_array(self.capacity) # make_array will be defined later
   #Length method
   def __len__(self):
      #It will return number of elements in the array
      return self.n
   def __getitem__(self, k):
      #it will return the elements at the index k
   if not 0 <=k <self.n:
      return IndexError('k is out of bounds')
   return self.A[k]
   def append(self, element):
   #checking the capacity
   if self.n == self.capacity:
      #double the capacity for the new array i.e
      self.resize(2*self.capacity) # _resize is the method that is defined later
   # set the n indexes of array A to elements
   self.A[self.n] = element
   self.n += 1
   def _resize(self, new_cap): #new_cap is for new capacity
   #declare array B
   B = self.make_array(new_cap)
   for k in range(self.n):
      B[k] = self.A[k] # referencing the elements from array A to B
      #ones refered then
   self.A = B # A is now the array B
   self.capacity = new_cap # resets the capacity
   #making the make-array method using ctypes
   def make_array(self,new_cap):
      return (new_cap * ctypes.py_object)()
arr = DynamicArray()

동적 클래스를 사용할 준비가 되었기 때문에 이것으로 무언가를 시도해보자 -

>>> len(arr)
0
>>> arr.append(1)
>>> #First item entered
>>> len(arr)
1
>>> arr.append('Tutorialspoint')
>>> #second item entered
>>> len(arr)
2
>>> arr[1]
'Tutorialspoint'

그게 다야, 우리는 우리 고유의 동적 배열을 만들었고 파이썬에서 목록인 배열의 크기를 조정할 수 있습니다.