現在、私はPythonを使用してデータ構造のコースを持っています。 本書では、1D配列構造と2D配列を実装するための2つの異なるクラスが含まれています。2次元配列クラスからオブジェクトを作成する
import ctypes
class Array:
def __init__(self, size):
assert size > 0, "Array size must be > 0"
self._size = size
PyArrayType = ctypes.py_object * size
self._elements = PyArrayType()
self.clear(None)
def len(self):
return self._size
def getitem(self, index):
assert index >= 0 and index < self.len(), "Array subscript out of range"
return self._elements[index]
def setitem(self, index, value):
assert 0 <= index < self.len(), "Array subscript out of range"
self._elements[index] = value
def clear(self, value):
for i in range(self.len()):
self._elements[i] = value
def iter(self):
return ArrayIterator(self._elements)
クラスArrayIterator: DEF INIT(自己、theArray): self._arrayRef = theArray self._curNdx = 0 DEF ITER(自己):1Dアレイについて
リターン自己 デフ次(自己): E: self._curNdx < LEN(self._arrayRef)の場合ntry = self._arrayRef [self._curNdx] self._curNdx + = 1 戻りエントリ他 : 昇給を呼び出すとStopIteration私はそれがどのように動作するかを理解するために、次のコードを使用し
class Array2D :
def __init__(self, numRows, numCols):
self._theRows = Array(numRows)
for i in range(numRows) :
self._theRows[i] = Array(numCols)
def numRows(self):
return len(self._theRows)
def numCols(self):
return len(self._theRows[0])
def clear(self, value):
for row in range(self.numRows()):
row.clear(value)
def __getitem__(self, ndxTuple):
assert len(ndxTuple) == 2, "Invalid number of array subscripts."
row = ndxTuple[0]
col = ndxTuple[1]
assert row >= 0 and row < self.numRows() \
and col >= 0 and col < self.numCols(), \
"Array subscript out of range."
the1dArray = self._theRows[row]
return the1dArray[col]
def __setitem__(self, ndxTuple, value):
assert len(ndxTuple) == 2, "Invalid number of array subscripts."
row = ndxTuple[0]
col = ndxTuple[1]
assert row >= 0 and row < self.numRows() \
and col >= 0 and col < self.numCols(), \
"Array subscript out of range."
the1dArray = self._theRows[row]
the1dArray[col] = value
:
arr = Array(5)
arrLen = arr.len()
arr.clear(0)
for i in range (arrLen):
print arr.getitem(i)
print "The length of the array = ",arrLen
print "Enter 5 numbers"
for i in range (arrLen):
#n = raw_input("num = ")
arr.setitem(i,i)
for i in range (arrLen):
print arr.getitem(i)
print"values are ", arr.iter()
しかし、2D配列をどのように呼び出すか分かりませんでした。
ArrMulti = Array2D(3, 4)
と私は次のエラーました:だから、誰かがどのように2次元配列オブジェクトを作成する方法を教えてくださいすることができます
File "MultiArrayADT.py", line 46, in __init__
self._theRows[i] = Array(numCols)
AttributeError: Array instance has no attribute '__setitem__'
を。