【发布时间】:2021-09-25 09:27:54
【问题描述】:
我必须为基于数组的堆栈编写一个推送方法,该堆栈被实现为 ArrayStack 类。
import ctypes
from typing import Any
def _new_array(capacity: int) -> 'py_object_Array_<capacity>':
"""Return a new array with the specified capacity that stores
references to Python objects.
"""
if capacity < 1:
raise ValueError('_new_array: capacity must be >= 1')
PyCArrayType = ctypes.py_object * capacity
a = PyCArrayType()
for i in range(len(a)):
a[i] = None
return a
创建 ArrayStack 的实例使用上面的 _new_array() 方法
class ArrayStack:
def __init__(self, iterable=[]) -> None:
self._n = 0 # number of elements stored in the stack
self._items = _new_array(1) # backing array
for elem in iterable:
self.push(elem)
使用 append 方法如下:self._items.append(x),给了我一个错误'py_object_Array_1' object has no attribute 'append',所以我使用了self._items[0],但它不会将元素推送到堆栈
def push(self, x: Any) -> None:
self._items[0] = x
你能告诉我我做错了什么吗?谢谢
【问题讨论】:
标签: python python-3.x stack